Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 313
Edward Avatar asked Sep 08 '26 04:09

Edward


1 Answers

"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 (i.e. no errors ) and if statement is evaluated as false, as value of x is null which does not match name.

like image 123
Bill Avatar answered Sep 11 '26 03:09

Bill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!