Bash:变量未正确扩展 [英] Bash: variable not getting expanded properly

查看:52
本文介绍了Bash:变量未正确扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用变量来重命名文件.但是,当我将变量插入文件名的开头时,事情无法按预期进行.

I am trying to use variable in renaming a file. However, I when insert the variable to the beginning of the filename, things does not work as expected.

在这种情况下,我进行了文件名测试:

Here's the case, I have a file name test:

$ ls
test

和一个变量 i=1

将变量添加到文件名的末尾或中间时,它起作用:

When adding the variable to the end or middle of filename, it works:

$ mv test test_$i
$ ls
test_1

将变量添加到文件名的开头时,它不起作用:

When adding the variable to the beginning of filename, it doesn't work:

$mv test_1 test  
$mv test $i_test
mv: missing destination file operand after 'test'
Try 'mv --help' for more information.

更糟糕的是,当我的文件名中包含扩展名时,该文件将被删除.

And even worse, when there is extension in my filename, the file will be removed.

$ touch test.try
$ ls
test.try
$ mv test.try $i_test.try
$ ls
 (nothing!)

有人可以向我解释吗?是bug还是我不知道的东西?

Can anyone explain this to me? Is it a bug or something I don't know?

推荐答案

您需要在变量名称前后加上{},以使其与文字的其余部分保持歧义(请记住,_是标识符中的有效字符):

You need to put {} around the variable name to disambiguate it from the rest of the literal (remember, _ is a valid character in an identifier):

mv test.try ${i}_test.try

或者使用双引号,这可以防止出现单词拆分和乱码的情况:

or, use double quotes, which gives you protection against word splitting and globbing:

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变量中的花括号?

这篇关于Bash:变量未正确扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆