Jump to content

Case statements

From Squishu Wiki

General

  • it's a good way to deal with user input

Syntax

case variable in
  pattern [ | pattern] ...) statements;;
  pattern [ | pattern] ...) statements;;
...
esac

Examples

echo "Is it morning? Please answer yes or no"
read timeofday

case "timeofday" in
  yes) echo "Good Morning";;
  no ) echo "Good Afternoon";;
  y  ) echo "Good Morning";;
  n  ) echo "Good Afternoon";;
  *  ) echo "Sorry, answer not recognized";;
esac
  • The * will match all strings to it's good at the end
  • Here is a concise version of the same
case "$timeofday" in
  yes | y | Yes | YES) echo "Good Morning";;
  n* | N*)             echo "Good Afternoon";;
  * )                  echo "Sorry, answer not recognized";;
esac
  • Here is a version with multiple statements
case "$timeofday" in
  yes | y | Yes | YES )
    echo "Good Morning"
    echo "Up bright and early today"
    ;;
  [nN]*)
    echo "Good Afternon"
    ;;
  *)
    echo "Sorry your answer isn't recognized"
    echo "Please answer yes or no"
    exit 1
    ;;
esac