Conditions, test and case

if runs a command and branches on its exit status — which is why an empty answer is reported as zero.

What you'll learn
  • Explain how if uses exit statuses
  • Compare numbers and strings with [ ], [[ ]] and (( ))
  • Match patterns with case
echo "Please enter a number: "
read num

if [ $num -gt 0 ]; then
  echo "$num is positive"
elif [ $num -lt 0 ]; then
  echo "$num is negative"
else
  echo "$num is zero"
fi

In most languages if takes a boolean. In Bash it takes a command, runs it, and looks at its exit status: 0 means success, so the branch is taken; anything else means failure. [ is an ordinary command (also called test), and ] is just its last argument. [ 5 -gt 0 ] exits with 0, [ -3 -gt 0 ] with 1.

What happens with bad input

Because $num is unquoted, Bash expands it and splits it into words before [ sees anything. Run with real input, the script behaves like this:

Typed [ receives Result
5 [ 5 -gt 0 ] “5 is positive”
-3 [ -3 -gt 0 ], then [ -3 -lt 0 ] “-3 is negative”
(Enter) [ -gt 0 ] unary operator expected, then “ is zero”
abc [ abc -gt 0 ] integer expression expected, then “abc is zero”
1 2 [ 1 2 -gt 0 ] too many arguments, then “1 2 is zero”
Pick what the user typed and follow the words that reach [ after expansion. A malformed test exits with status 2, which if treats like false, so the script falls through to else.

An error inside a test is just another non-zero status, so the script cannot tell “false” from “broken” and reports zero. The fix is to validate first:

if [[ ! $num =~ ^-?[0-9]+$ ]]; then
  echo "not an integer: '$num'" >&2
  exit 1
fi
if (( num > 0 )); then ...

[[ ]] is Bash’s built-in test: it does not split words, so an empty $num stays one empty argument, and it supports =~ regular expressions. For arithmetic, (( )) reads like C and needs no -gt.

case

control_flow_case.sh matches a string against patterns:

case $fruit in
    "apple")  echo "This is a red fruit." ;;
    "banana") echo "This is a yellow fruit." ;;
    *)        echo "Unknown fruit." ;;
esac

The first matching pattern wins and ;; ends its branch. Patterns are glob patterns, so [Aa]pple, *.txt and apple|pear all work. For mango only the catch-all * matches, and the script prints “Unknown fruit.”

Try it yourself. Add the validation above to control_flow_if_else.sh and test it with an empty line, abc and -0. Then extend the case script so that Apple, APPLE and apple all match one branch, using a single pattern.

View source on GitHub →