3

我在教程中看到了两种在 BASH shell 中为 if 语句执行语法的方法:

除非我在变量周围加上引号并添加额外的 [ 和 ],否则这将不起作用:

if [[ "$step" -eq 0 ]]

这个工作没有在变量周围加上引号,并且不需要额外的 [ 和 ] :

if [ $step -ge 1 ] && [ $step -le 52 ]

哪个是正确和最佳实践?有什么区别?谢谢!

4

1 回答 1

3

“引用变量时,通常建议将其名称用双引号引起来” ——http: //tldp.org/LDP/abs/html/quotingvar.html

if [ $step -ge 1 ] && [ $step -le 52 ] 可以替换为

if [ "$step" -ge 1 -a "$step" -le 52 ]

if [[ "$step" -eq 0 ]]可以替换为if [ "$step" -eq 0 ]

另外,假设您有以下脚本:

#!/bin/bash
if [ $x -eq 0 ]
then
        echo "hello"
fi

运行脚本时出现此错误 -example.sh: line 2: [: -eq: unary operator expected

但是使用if [ "$x" -eq 0 ]

运行脚本时会出现不同的错误——example.sh: line 2: [: : integer expression expected

因此,最好将变量放在引号内......

if [[ .... ]]regex语法在条件语句中特别有用——http: //honglus.blogspot.com/2010/03/regular-expression-in-condition.html

编辑:当我们处理字符串时——

#!/bin/bash
if [ $x = "name"  ]
then
        echo "hello"
fi

运行脚本时出现此错误 -example.sh: line 2: [: =: unary operator expected

但是,如果你使用if [ "$x" = "name" ]它运行良好(即没有错误)并且if语句被评估为false,因为它的值xnull匹配name

于 2013-05-12T20:33:32.873 回答