我试图在重命名文件时使用变量。但是,当我将变量插入文件名的开头时,事情不能按预期工作。
在这种情况下,我有一个文件名测试:
$ ls
test
和变量
i=1
将变量添加到文件名的末尾或中间时,它可以工作:
$ mv test test_$i
$ ls
test_1
将变量添加到文件名的开头时,它不起作用:
$mv test_1 test
$mv test $i_test
mv: missing destination file operand after 'test'
Try 'mv --help' for more information.
更糟糕的是,当我的文件名中有扩展名时,该文件将被删除。
$ touch test.try
$ ls
test.try
$ mv test.try $i_test.try
$ ls
(nothing!)
任何人都可以向我解释这个吗?这是一个我不知道的错误吗?
答案 0 :(得分:3)
您需要在变量名称周围添加{}
以使其与文字的其余部分消除歧义(请记住,_
是标识符中的有效字符):
mv test.try ${i}_test.try
或使用双引号,它可以防止分词和通配:
mv test.try "${i}"_test.try
在您的代码中:
$i_test => shell treats "i_test" as the variable name
$i_test.try => shell treats "i_test" as the variable name ('.' is not a valid character in an identifier)
mv test.try $i_test.try => test.try got moved to .try as "$i_test" expanded to nothing. That is why ls didn't find that file. Use 'ls -a' to see it.
请参阅此相关帖子:When do we need curly braces in variables using Bash?