-
Notifications
You must be signed in to change notification settings - Fork 39
Description
if [ condition1 ]; then command1;
elif [ condition2 ]; then command2;
else command3; fi
There are competing ideas for how this kind of thing should be structured. Personally, I prefer this:
if [ condition1 ]; then
command1
elif [ condition2 ]; then
command2
else
command3
fi
Nesting the indentation in this way more clearly defines where an action is taking place.
Next, if this is using a more recent shell like ksh, bash or zsh, [[]] should be preferred.
Next,
| -a | check if file exists |
|---|
-e is the more canonical option here, and it makes more sense i.e. if file -exists...
| == | check if both the strings are equal |
|---|
== and != are not defined within single bracket [], so using them introduces unpredictability to your code. I prefer to leave these operators for arithmetic tests and use a more classic style for string tests e.g.
[ a == b ] # bad
[ ! a = b ] # better
! [ a = b ] # also better
[[ ! a = b ]] # also better
! [[ a = b ]] # also better
[[ a == b ]] # technically works but it's weird using an arithmetic operator for strings
(( x == y )) # Nice, arithmetic operator in an arithmetic context
(( x != y )) # Again, arithmetic operator in an arithmetic context
Which brings us on to the number comparators. -eq, -ne etc are older, somewhat archaic syntax. ==, !=, >, <, >=, and <= within (( )) make it clearer to the reader of your code that you're performing an arithmetic operation.
Another typo in this section: descr>iption