Let’s say we want to add the following switches to a script:

Note the use of short / long options

The easy way:


while [ "$#" -gt 0 ]
do
    case "$1" in
        -u|--user)
            echo 'Do something with "$1"'; shift;;
        -w|--wall)
            echo 'Do something with "$1"'; shift;;
        esac
done

It loops until the number of arguments to the script ($#) drops to zero.

And now, the getopt way:


TEMP=$(getopt --options uw \
              --longoptions user,wall \
              --name "$0" \
              -- "$@")
if [ $? != 0 ]; then exit 1; fi
eval set -- "$TEMP"

while true
do
    case "$1" in
        -u|--user)
            echo 'Do something with "$1"'; shift;;
        -w|--wall)
            echo 'Do something with "$1"'; shift;;
        --)
            shift; break;;
        *)
            echo "Unknown switch"
            exit 1
    esac
done

The second version allows extra things like: