Wednesday, November 30, 2011

While-Do Loopy and Case-Esac Overstatements

By now, I hope everyone know if-then statements.  Just in case, here's a super quick
example:

if [ $num -eq 5 ]
then
                echo "The number is 5!"
fi

If something is true, then do this, and end the command with "fi".  While-do loops and
case-esac statements aren't much different.  A quick example for while:

typeset -i num=0               #create an integer,
                               #not always used for while,
                               #just an example

while [ $num -lt 5 ]           #keep doing this while
                               #num is less than 5
do                             #start loop
                echo "$num"    #say the number num
                num=$num+1     #add 1 to number
done                           #done with this loop

By adding other commands, the while loop can get to look very complicated, but the basic
archetecture is the same each time.  Now for an example case-esac:

read input                           #read input from the user,
                                     #again just an example

case $input in                       #use the variable $input
                1) echo "one";;      #if input is "1", say "one"
                2) echo "two";;      #if input is "2", say "two"
                a) echo "AAA";;      #if input is "a", say "AAA"
                hello) echo "hi";;   #if "hello", say "hi"
                q) echo "goodbye;;   #if "q", say "goodbye"
                *) echo "huh?";;     #if anything different
                                     #than above, say "huh?"
esac                                 #done with case statement

I hope this helps.  Until next time, codemonkeys!

No comments:

Post a Comment