【问题标题】:Bash: variable not getting expanded properly [duplicate]Bash:变量没有正确扩展[重复]
【发布时间】:2017-02-13 04:54:23
【问题描述】:

我正在尝试使用变量来重命名文件。但是,当我将变量插入文件名的开头时,事情并没有按预期工作。

这样的话,我有一个文件名测试:

$ 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 "$i"_test
  • 请注意,丢失的文件已重命名为 .try — 它仍然存在(使用 ls -a 查看)。

标签: bash variables


【解决方案1】:

您需要在变量名周围加上 {} 以消除其与文字其余部分的歧义(请记住,_ 是标识符中的有效字符):

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?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多