在大多数情况下,引用没有空格或特殊字符的字符串严格等同于根本不引用。
但是,在某些情况下,引用会有所不同。
防止别名
许多 Linux 发行版会自动为 ls 或 grep 等程序设置别名,例如:
alias ls='ls --color=auto'
alias grep='grep --color=auto'
如果调用引用的命令,别名不会被扩展:
ls / # shows the root files and folders with colors
'ls' / # shows the root files and folders without any color
即使命令被部分引用也不使用别名:
'l's / # shows the root files and folders without any color
(不过,我强烈建议不要这样做)
保留关键字
某些关键字不能被引用。例如,这将起作用:
time cat $myfile
但这会失败:
'time' cat $myfile
-bash: time: command not found
波浪号扩展
波浪号~ 可用于访问主目录。单独指向当前用户的主目录:
ls ~
当直接跟用户名时,它指向该用户的主目录:
ls ~root
引用波浪号时,目录不会展开,shell 会尝试查找包含波浪号的文件:
ls '~'
ls: 无法访问~: 没有这样的文件或目录
测试
[[ ]] 操作符可以使用test 命令,如-f、-e 等,但不能引用该指令。
[[ -e /tmp ]] && echo /tmp exists || echo /tmp is missing
/tmp 存在
[[ '-e' /tmp ]] && echo /tmp exists || echo /tmp is missing
-bash:需要条件二元运算符
-bash: `/tmp' 附近的语法错误
结论
在很多情况下,引用确实会产生影响。我认为第一种情况是您的作者编写代码的原因。
PS。这个列表并不详尽,我特别省略了空格、星号、管道、& 号等情况,因为我假设你已经知道为什么有人要引用它们。