CASE-instructies

Introductie tot Bash-scripting

Alex Scriven

Data Scientist

Waarom CASE-instructies?

Case-instructies zijn vaak efficiënter dan IF bij meerdere of complexe voorwaarden.

Stel dat je dit wilt testen:

  • Als een bestand sydney bevat, verplaats het naar de map /sydney
  • Als een bestand melbourne of brisbane bevat, verwijder het
  • Als een bestand canberra bevat, hernoem naar IMPORTANT_filename, waarbij filename de originele bestandsnaam is
Introductie tot Bash-scripting

Een complexe IF

Je kunt meerdere IF’s schrijven zoals:

  • Deze code runt grep op het eerste ARGV-argument voor de voorwaarde.
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
  • Best complex en herhalend, toch?
Introductie tot Bash-scripting

Bouw een CASE-instructie

  • Begin met kiezen tegen welke variabele of string je matcht
    • Je kunt hier een shell-in-een-shell aanroepen!
  • Voeg zoveel patronen en acties toe als je wilt.
    • Je kunt regex gebruiken voor PATTERN, zoals Air* (begint met Air) of *hat* (bevat hat).
  • Scheid patroon en uit te voeren code met een sluit-haakje en eindig commando’s met dubbele puntkomma

Basisopzet CASE:

case 'STRINGVAR' in

PATTERN1) COMMAND1;; PATTERN2) COMMAND2;;
Introductie tot Bash-scripting

Bouw een CASE-instructie

 

  • *) DEFAULT COMMAND;;

    • Het is gebruikelijk (niet verplicht) om af te sluiten met een standaardopdracht die draait als geen patroon matcht.
  • esac Tot slot het afsluitwoord: 'esac'

    • Dat is 'case' achterstevoren!

Basisopzet CASE:

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

*) DEFAULT COMMAND;;
esac
Introductie tot Bash-scripting

Van IF naar CASE

Onze oude IF-instructie:

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

Onze nieuwe CASE-instructie:

case $(cat $1) in

*sydney*) mv $1 sydney/ ;; *melbourne*|*brisbane*) rm $1 ;; *canberra*) mv $1 "IMPORTANT_$1" ;;
*) echo "No cities found" ;; esac
Introductie tot Bash-scripting

Laten we oefenen!

Introductie tot Bash-scripting

Preparing Video For Download...