如果没有双引号变量,BASH 脚本 mv 命令将无法工作。为什么?

Dig*_*nce 1 variables bash double-quotes

我今天写了一个脚本如下:

echo "Enter a directory path"

read dir

for file in $dir/[!.]*;
    do
        f=`echo $file | sed 's/ /_/g'`
        mv "${file}" "${f}"  
    done
Run Code Online (Sandbox Code Playgroud)

最初,mv 命令写为:

mv ${file} ${f}
Run Code Online (Sandbox Code Playgroud)

但那条线正在抛出

usage: mv [-f | -i | -n] [-v] source target
   mv [-f | -i | -n] [-v] source ... directory
Run Code Online (Sandbox Code Playgroud)

我能够使用谷歌找出变量需要用双引号引起来,但我仍然不明白为什么这样做可以解决问题?
谢谢!

Cha*_*ffy 5

在 shell 中,引用可以防止字符串分割和全局扩展。如果您不对变量加双引号,则您不知道运行这些解析步骤后每个变量可能会扩展为多少个参数。

那是:

mv $foo $bar
Run Code Online (Sandbox Code Playgroud)

……可能会变成……

mv ./first word second word third word destination-file
Run Code Online (Sandbox Code Playgroud)

如果

foo='./first word second word third word'
bar='destination-file'
Run Code Online (Sandbox Code Playgroud)

同样,考虑文件名包含 glob 表达式的情况:

foo='hello * world'
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您的mv命令将获取当前目录中所有文件的列表


...或者,考虑参数为空时的情况:

foo='hello world'
bar=''
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您将尝试重命名名为 的文件,而不是(正确地)收到不能使用 0 字节名称的文件的错误helloworld简单$bar地消失。