Bash Shell: What is the differences in syntax?

I've seen two ways in tutorials to do syntax for if statements in BASH shell:

This one wouldn't work unless I put quotes around the variable and added additional [ and ]:

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

This one worked without putting quotes around the variable and the additional [ and ] weren't needed:

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

Which is correct and best practice? What are the differences? Thanks!


"When referencing a variable, it is generally advisable to enclose its name in double quotes" -- http://tldp.org/LDP/abs/html/quotingvar.html

if [ $step -ge 1 ] && [ $step -le 52 ] can be replaced as

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

if [[ "$step" -eq 0 ]] can be replaced as if [ "$step" -eq 0 ]

Also, suppose you have the following script:

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

You get this error when you run the script -- example.sh: line 2: [: -eq: unary operator expected

But using if [ "$x" -eq 0 ]

You get a different error when you run the script -- example.sh: line 2: [: : integer expression expected

Thus, it is always best to put variables inside quotes...

if [[ .... ]] syntax is particularly useful when you have regex in the condition statement -- http://honglus.blogspot.com/2010/03/regular-expression-in-condition.html

EDIT: When we deal with strings --

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

You get this error when you run the script -- example.sh: line 2: [: =: unary operator expected

But, if you use if [ "$x" = "name" ] it runs fine (ie no errors ) and if statement is evaluated as false , as value of x is null which does not match name .

链接地址: http://www.djcxy.com/p/97050.html

上一篇: 方括号和

下一篇: Bash Shell:语法有什么区别?