Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash:变量未正确展开_Bash_Variables - Fatal编程技术网

Bash:变量未正确展开

Bash:变量未正确展开,bash,variables,Bash,Variables,我试图在重命名文件时使用变量。但是,当我在文件名的开头插入变量时,事情并没有按预期的那样进行 在这种情况下,我有一个文件名测试: $ 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

我试图在重命名文件时使用变量。但是,当我在文件名的开头插入变量时,事情并没有按预期的那样进行

在这种情况下,我有一个文件名测试:

$ 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!)

谁能给我解释一下吗?它是一个bug还是我不知道的东西?

您需要在变量名周围放置
{}
,以消除它与文本其余部分之间的歧义(请记住,
\uu
是标识符中的有效字符):

或者,使用双引号,这样可以防止分词和全局搜索:

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.


请参阅此相关帖子:

始终引用您的变量。尝试
mv test“$i”\u test
注意,丢失的文件已重命名为
。尝试
-它仍然存在(使用
ls-a
查看它)。
$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.