Introductie tot Bash-scripting
Alex Scriven
Data Scientist
Case-instructies zijn vaak efficiënter dan IF bij meerdere of complexe voorwaarden.
Stel dat je dit wilt testen:
sydney bevat, verplaats het naar de map /sydneymelbourne of brisbane bevat, verwijder hetcanberra bevat, hernoem naar IMPORTANT_filename, waarbij filename de originele bestandsnaam isJe kunt meerdere IF’s schrijven zoals:
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
PATTERN, zoals Air* (begint met Air) of *hat* (bevat hat).Basisopzet CASE:
case 'STRINGVAR' inPATTERN1) COMMAND1;; PATTERN2) COMMAND2;;
*) DEFAULT COMMAND;;
esac Tot slot het afsluitwoord: 'esac'
Basisopzet CASE:
case 'STRING' in PATTERN1) COMMAND1;; PATTERN2) COMMAND2;;*) DEFAULT COMMAND;;esac
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