Complete Communications Engineering

Linux shell scripts are used for automation, and automation usually requires decision making.  There are a few ways to make decisions in shell scripts.  Three of these are the if, while and case keywords.  These keywords (and others) are built into the shell language, so they are reserved and can’t be used as variable names.  The if and while keywords both execute a given command, then proceed depending on if the command succeeds or fails.  Success or failure is determined by the command’s exit code.  If the code is 0, it succeeded.  For any other value, it failed.  The syntax for if and while is as follows:

if command1

then

    # run if command1 succeeded

elif command2

    # run if command2 succeeded

else

    # run if both command1 and command2 failed

fi

 

while command

do

    # keep running this code and executing command as long as command succeeds

done

The case keyword is a bit different in that it does not execute a command but instead operates on a given value.  The syntax for case is as follows:

case $VARIABLE in

    pattern1)

        # run if $VARIABLE matches pattern1

    ;;

    pattern2)

        # run if $VARIABLE matches pattern2

    ;;

    *)

        # default condition to run if no other pattern matches

    ;;

esac

A common use case for decision making is comparing the value of two variables.  This can be done with either the ‘test’ or ‘[‘ commands.  They both use the same syntax, except that ‘[‘ requires an ‘]’ as the last argument.  The following examples show comparing string and number values using the ‘[‘ command:

STRING1 = “FOO”

STRING2 = “BAR”

if [ $STRING1 == $STRING2 ]

then

    # Strings are equal (will not run)

else

    # Strings are not equal (will run)

fi

 

NUMBER1 = 5

NUNBER2 = 10

if [ $NUMBER1 eq $NUMBER2 ]

then

    # Numbers are equal (will not run)

else

    # Numbers are not equal (will run)

fi