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

 



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