Bash Shell:语法有什么不同?

时间:2013-05-12 20:27:06

标签: bash if-statement syntax

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

除非我在变量周围添加引号并添加其他[和]:

,否则这个不会起作用
if [[ "$step" -eq 0 ]]

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

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

哪个是正确的最佳做法?有什么区别?谢谢!

1 个答案:

答案 0 :(得分: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,因为x的值是{{1} }与null不匹配。

相关问题