Introduction to Bash Scripting
Alex Scriven
Data Scientist
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:
sydney
then move it into the /sydney
directorymelbourne
or brisbane
then delete itcanberra
then rename it to IMPORTANT_filename
where filename
was the original filenameYou could construct multiple IF statements like so:
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
PATTERN
. Such as Air*
for 'starts with Air' or *hat*
for 'contains hat'.Basic CASE statement format:
case 'STRINGVAR' in
PATTERN1) COMMAND1;; PATTERN2) COMMAND2;;
*) DEFAULT COMMAND;;
esac
Finally, the finishing word is 'esac'
Basic CASE statement format:
case 'STRING' in PATTERN1) COMMAND1;; PATTERN2) COMMAND2;;
*) DEFAULT COMMAND;;
esac
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