Bash conditionals

From wikinotes
Revision as of 19:23, 11 May 2018 by Will (talk | contribs) (→‎commands in conditionals)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

if statements

if [[ "$var1" = "2" ]] ; then
   echo 'condition 1'

elif [[ "$var1" = "3" ]] ; then
   echo 'condition2'

else
   echo 'no conditions met'
fi

case statements

case $var in
    -h|--help)
        echo "help message"
        ;;
    -l|--list)
        echo "a, b, c, ..."
        ;;
    test*)
        echo "test run..."
        ;;
    *)
        echo "no conditions met"
        ;;
esac

&&, ||

[[ "1" == "1" ]] && echo "true"    # if true, then
[[ "1" == "2" ]] || echo "false"   # if false, then

commands in conditionals

It is entirely valid to evaluate a bash command inline within an if/case statement.

if [[ "$(command -o blah)" == "blah" ]]; then
    # ..code..
fi

You can also test a function/executable's returncode

if command -o blah
    # if command succeeded
else
    # if command failed
fi