Bash / sh if statement syntax

In the various manuals and scripts that I come across, people tend to use different if syntax expressions. What is the difference and what are the best practices? I believe that all of the following statements and many other options will return true:

bar="foo" if [ "foo" = "foo" ] if [[ "foo" == $bar ]] if [ "foo" = "$bar" ] if [[ "foo" = "$bar" ]] if [[ "foo" -eq $bar ]] 
+7
linux bash
source share
3 answers

As far as I understand,

= expects string

-eq expects integers

"$ bar" for letter matches, i.e. z * can expand, but "z *" will literally match the char pattern.

The difference between [] and [[]] is that in the last word splitting and extension of the path name are not performed, but are in the first.

Plus [[]] allows you to use additional operators:

& & (ALSO), || (OR),> (String1 is lexically larger than String2), <(String1 is lexically smaller than String2)

The comparison operator == works differently in a test with two brackets than in separate brackets.

[[$ a == z *]] # True if $ a starts with "z" (pattern matching).

[[$ a == "z *"]] # True if $ a is equal to z * (literal match).

[$ a == z *] # Performs file splitting and word splitting.

["$ a" == "z *"] # True if $ a is equal to z * (literal match).

For more information contact http://tldp.org/LDP/abs/html/comparison-ops.html

+5
source share

[ is bash builtin, [[ is bash keyword. It is best to use [[ if the script should not be compatible with other shells (for example, if it starts with #!/bin/bash ) and use [ only for compatibility with the Bourne shell. See http://mywiki.wooledge.org/BashFAQ/031 .

+3
source share

I recommend case / esac.

 case "$foo" in "bar" ) echo "bar";; *) echo "not equal";; esac 

Do not worry about the different syntax.

+2
source share

All Articles