Bash programming/Conditional statements

if...elif...else...fi Example

edit

The following will check the arguments passed and print the first argument.

if [ $# -lt 1 ]; then
    #If fewer than 1 parameter are given, then display an error and exit
    echo "please enter at least one argument value"
    exit
elif [ $# -gt 3 ]; then
    # If more than 3 parameters are given, then display an error and exit  
    echo "Please use 3 or less parameters."
    exit
else
    echo "Here is first argument:"
    echo $1  
fi

This program demonstrates a few things of note. The first is the construction of the if, elif, else ladder. Note that it is terminated by "fi" (if spelled backwards), a command that serves as an "endif" if you will.

Also, this program demonstrates one way to get the number of parameters or arguments passed to the script when it was called. It is common to pass arguments or parameters to scripts as one often does with programs:

./script.sh arg1 "argument two" arg3

This demonstrates passing three arguments to the script, and the variable $# would be set to 3.

This script also demonstrates one way to test variables, within the [ ] construct and using the -gt (greater than) operator. Other options include -lt (less than), -ne (not equal to), -ge (greater than or equal to), and many others.

Though, the use of the [ ] construct is widely popular, the new [[ ]] bash construct should be preferred as it is more resilient and less error-prone. The following is the same script as above but with the [[ ]] construct.

if [[ $# < 1 ]]; then
    #If fewer than 1 parameter are given, then display an error and exit
    echo "please enter at least one argument value"
    exit
elif [[ $# > 3 ]]; then
    # If more than 3 parameters are given, then display an error and exit  
    echo "Please use 3 or less parameters."
    exit
else
    echo "Here is first argument:"
    echo $1  
fi

if... check Null variable example

edit

Both examples are equivalente and check for a null variable:

if [ "$1" = "" ]; then
        echo "Variable $1 is null";
else
        echo "Variable $1 is NOT null";
fi

Note that there must be a space on each side of the brackets, unless there is a non-word-constituent character like ";") [1]

if [ -z "$1" ]; then
        echo "Variable $1 is null";
else
        echo "Variable $1 is NOT null";
fi

Switch Statement

edit
case ${RETCODE} in
0)
    echo "File moved successfully.";;
1)
    echo "Error: File not found"
2)
    echo "Error: Destination not found"
*)
    echo "Error: Undefined error"
esac

References

edit