Skip to content

Instantly share code, notes, and snippets.

@estysdesu
Last active July 21, 2019 06:31
Show Gist options
  • Save estysdesu/547f2047eb750d259bab720571ccad3f to your computer and use it in GitHub Desktop.
Save estysdesu/547f2047eb750d259bab720571ccad3f to your computer and use it in GitHub Desktop.
[Shell: classic control flow (conditionals, loops)] #if #case #then #sh #while #for #if #case #switch #else
##### if, elif, else, fi (CONDITIONAL) #####
# https://www.netacad.com/courses/os-it/ndg-linux-essentials --> Ch11: Basic Scripting
if [ "$1" = "hello" ]; then # square brackets are same as test command `test "$1" = "hello"`
echo "hello yourself"
elif [ "$1" = "goodbye" ]; then
echo "nice to have met you"
echo "I hope to see you again"
else
echo "I didn't understand that"
fi
##### case (CONDITIONAL; SWITCH) #####
# http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_03.html
space=`df -h | awk '{print $5}' | grep % | grep -v Use | sort -n | tail -1 | cut -d "%" -f1 -`
case $space in
[1-6]*)
Message="All is quiet."
;; # denote end of case section
[7-8]*)
Message="Start thinking about cleaning out some stuff. There's a partition that is $space % full."
;;
9[1-8])
Message="Better hurry with that new disk... One partition is $space % full."
;;
99)
Message="I'm drowning here! There's a partition at $space %!"
;;
*)
Message="I seem to be running with an nonexistent amount of disk space..."
;;
esac
echo $Message
##### for (LOOP) #####
# loop through list of strings
SERVERS="serverA serverB serverC"
for S in $SERVERS; do
echo "Doing something to $S" #serverA --> serverB --> serverC
done
# loop through list of files
for f in *; do
echo "$f"
done
##### while (LOOP) #####
# loop through with test conditon
i=0
while [ $i -lt 10 ]; do
echo $i
(( i++ )) # increase x in place; same as `i=$(( $i + 1 ))`
done
echo “Done counting”
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment