CASE statements

Introduction to Bash Scripting

Alex Scriven

Data Scientist

The need for CASE statements

Case statements can be more optimal than IF statements when you have multiple or complex conditionals.

Let's say you wanted to test the following conditions and actions:

  • If a file contains sydney then move it into the /sydney directory
  • If a file contains melbourne or brisbane then delete it
  • If a file contains canberra then rename it to IMPORTANT_filename where filename was the original filename
Introduction to Bash Scripting

A complex IF statement

You could construct multiple IF statements like so:

  • This code calls grep on the first ARGV argument for the conditional.
if grep -q 'sydney' $1; then
    mv $1 sydney/
fi
if grep -q 'melbourne|brisbane' $1; then
    rm $1
fi
if grep -q 'canberra' $1; then
    mv $1 "IMPORTANT_$1"
fi
  • Seems complex and repetitious huh?
Introduction to Bash Scripting

Build a CASE statement

  • Begin by selecting which variable or string to match against
    • You could call shell-within-a-shell here!
  • Add as many possible matches & actions as you like.
    • You can use regex for the PATTERN. Such as Air* for 'starts with Air' or *hat* for 'contains hat'.
  • Ensure to separate the pattern and code to run by a close-parenthesis and finish commands with double semi-colon

Basic CASE statement format:

case 'STRINGVAR' in

PATTERN1) COMMAND1;; PATTERN2) COMMAND2;;
Introduction to Bash Scripting

Build a CASE statement

 

  • *) DEFAULT COMMAND;;

    • It is common (but not required) to finish with a default command that runs if none of the other patterns match.
  • esac Finally, the finishing word is 'esac'

    • This is 'case' spelled backwards!

Basic CASE statement format:

case 'STRING' in
  PATTERN1)
  COMMAND1;;
  PATTERN2)
  COMMAND2;;

*) DEFAULT COMMAND;;
esac
Introduction to Bash Scripting

From IF to CASE

Our old IF statement:

if grep -q 'sydney' $1; then
    mv $1 sydney/
fi

if grep -q 'melbourne|brisbane' $1; then
    rm $1
fi

if grep -q 'canberra' $1; then
    mv $1 "IMPORTANT_$1"
fi

Our new CASE statement:

case $(cat $1) in

*sydney*) mv $1 sydney/ ;; *melbourne*|*brisbane*) rm $1 ;; *canberra*) mv $1 "IMPORTANT_$1" ;;
*) echo "No cities found" ;; esac
Introduction to Bash Scripting

Let's practice!

Introduction to Bash Scripting

Preparing Video For Download...