Basic case statement

Instead of if/else statements, you can use case statements to evaluate a variable. Notice that esac is case backwards and is used to exit the case statement similar to fi for if statements.

Case statements follow this flow:

case $THING_I_AM_TO_EVALUATE in
  1) # Condition to evaluate is number 1 (could be "a" for a string too!)    echo "THING_I_AM_TO_EVALUATE equals 1"    ;; # Notice that this is used to close this evaluation  *) # * Signified the catchall (when THING_I_AM_TO_EVALUATE does not equal values in the switch)    echo "FALLTHOUGH or default condition"esac # Close case statement

The following is a working example:

#!/bin/bashVAR=10 # Edit to 1 or 2 and re-run, after running the script as is.case $VAR in
  1)    echo "1"    ;;

Get Bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.