In various guides and scripts I come across people tend to use different syntax of if statements. What's the difference and what are best practices? I believe all the following statements, and many more variants, will return true:
bar="foo"
if [ "foo" = "foo" ]
if [[ "foo" == $bar ]]
if [ "foo" = "$bar" ]
if [[ "foo" = "$bar" ]]
if [[ "foo" -eq $bar ]]
The if statement starts with the if keyword followed by the conditional expression and the then keyword. The statement ends with the fi keyword. If the TEST-COMMAND evaluates to True , the STATEMENTS gets executed. If TEST-COMMAND returns False , nothing happens; the STATEMENTS get ignored.
Syntax: if [ expression ] then statement fi. if-else statement. If specified condition is not true in if part then else part will be execute. Syntax if [ expression ] then statement1 else statement2 fi. if..elif..else..fi statement (Else If ladder)
A null string in Bash can be declared by equalizing a variable to “”. Then we have an “if” statement followed by the “-n” flag, which returns true if a string is not null. We have used this flag to test our string “name,” which is null.
As I understand it
= expects strings
-eq expects integers
"$bar" is for literal matches, i.e. z* may expand but "z*" will literally match the wildcard char.
The difference between [] and [[]] is that in the latter word splitting and path name expansion are not done, but are in the former.
Plus [[]] allows the additional operators :
&& (AND), || (OR), > (String1 lexically greater than String2), < (String1 lexically less than String2)
The == comparison operator behaves differently within a double-brackets test than within single brackets.
[[ $a == z* ]] # True if $a starts with an "z" (pattern matching).
[[ $a == "z*" ]] # True if $a is equal to z* (literal matching).
[ $a == z* ] # File globbing and word splitting take place.
[ "$a" == "z*" ] # True if $a is equal to z* (literal matching).
Check out http://tldp.org/LDP/abs/html/comparison-ops.html for more info
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With