bash case - ghdrako/doc_snipets GitHub Wiki
The case statement is used for multi-way branching based on the value of an expression.
case <variable> in
<pattern 1>)
<code to execute if expression matches pattern1>
;;
<pattern 2>)
<code to execute if expression matches pattern2>
;;
)
<code to execute if none of the patterns match>
;;
esac
case "$Variable" in
#List patterns for the conditions you want to meet
0) echo "There is a zero.";;
1) echo "There is a one.";;
*) echo "It is not null.";;
esac
read -p "How many shoes do you have?"
case value in
0|1)
echo "Not enough shoes! You can't walk"
;;
2)
echo "Awesome! Go walk!"
#...
;;
*)
echo "You got more shoes than you need"
#...
;;
esac
space_free=$( df -h | awk '{ print $5 }' | sort -n | tail -n 1 | sed 's/%//' )
case $space_free in
[1-5]*)
echo Plenty of disk space available
;;
[6-7]*)
echo There could be a problem in the near future
;;
8*)
echo Maybe we should look at clearing out old files
;;
9*)
echo We could have a serious problem on our hands soon
;;
*)
echo Something is not quite right here
;;
esac
case $CIRCLE_BRANCH in
"develop")
export ENVIRONMENT="dev"
export HEROKU_APP=dev-app
;;
"staging")
export ENVIRONMENT="staging"
export HEROKU_APP=staging-app
;;
"production")
export ENVIRONMENT="production"
export HEROKU_APP=production-app
;;
esac
file_to_process="report.pdf"
case "$file_to_process" in
*.txt)
echo "Processing a text file..."
;;
*.pdf)
echo "Converting PDF to text..."
pdftotext "$file_to_process"
;;
*.zip)
echo "Extracting archive..."
unzip "$file_to_process"
;;
*)
echo "Unknown file type!"
;;
esac
Using the ‘or’ operator (|) lets you combine patterns under a single case branch:
case "$response" in
yes | y | YES | Yes)
echo "Affirmative!"
;;
n | no | NO)
echo "Negative!"
;;
*)
echo "Please enter yes or no."
;;
esac
- https://www.tldp.org/LDP/abs/html/nestedloops.html Decision trees! Place another case within a pattern’s code for a second layer of decision-making:
case "$1" in
start)
case "$2" in
production)
run_production_server
;;
test)
run_test_server
;;
*)
echo "Specify environment ('production' or 'test')"
;;
esac
;;
# More primary options....
esac