我正在尝试使用变量重命名文件。但是,当我将变量插入到文件名的开头时,事情没有按预期工作。
情况如下,我有一个文件名测试:
$ 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!)
谁能向我解释一下吗?这是一个错误还是我不知道的东西?
你需要把{}
围绕变量名以消除它与其余文字的歧义(记住,_
是标识符中的有效字符):
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.
请参阅此相关帖子:在使用 Bash 的变量中什么时候需要花括号?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)