Skip to content

Corrections for 'if' section #5

@rawiriblundell

Description

@rawiriblundell
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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions