How to use a case statement in a BASH script

Home > Search > How-to
  by

A case statement is used to do something when a certain condition is true. For example, this case statement will return a certain result based on the day of the week.

#!/bin/bash
NOW=$(date +"%a")
case $NOW in
	Mon)	
		echo "Today is Monday";;
	Tue)
		echo "Today is Tuesday";;
	Wed)
		echo "Today is Wednesday";;
	Thu)
		echo "Today is Thursday";;
	Fri)
		echo "Today is Friday";;
	Sat|Sun)	
		echo "It is the weekend!";;
	*) ;;
esac

 

Another example

#!/bin/bash
read -P "What is your name?" myName
case $myName in
	Peter)	
		echo "My name is Peter, I am the dad";;
	Stewey)
		echo "My name is Stewey, I am the baby";;
	Meg)
		echo "My name is Meg, I am the daughter";;
	Chris)
		echo "My name is Chris, I am the son";;
	Lois)
		echo "My name is Lois, I am the mom";;
	Brian)	
		echo "My name is Brian, I am the dog";;
	*) 
        echo "I am nothing";;
esac

 


Command line options (parameters arguments switches)

One of the most practical uses of a case statement is to be able to pass command line options with a command. For example, lets say you have a bash script and you want options such as -v or --verbose and -h or --help.

~]# example.sh -v sample -h sample

 

A case statement can be used to create the verbose and help options. The $help and $verbose options with both contain a value of "sample" in this example.

ARGS=$(getopt -a --options v:h: --long "verbose:,help:" -n "example" -- "$@")
eval set -- "$ARGS"
while true; do
  case "$1" in
    -v|--verbose)
      verbose="$2"
      shift 2;;
    -h|--help)
      help="$2"
      shift 2;;
    --)
      break;;
     *)
      printf "Unknown option %s\n" "$1"
      exit 1;;
  esac
done

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments