Bash Tips: Testing Arguments

by
Annika Backstrom
in misc, on 11 August 2003. It is tagged and #Scripting.

Ever want to test command line arguments in bash, mixing arguments and execution options? I have. Here's one way to do it:

#!/bin/sh

filelist=

until [ -z "$1" ]; do
    # use a case statement to test vars. we always test
    # test $1 and shift at the end of the for block.
    case $1 in
        --home|-h )
            # shift, so the string after --home becomes
            # our new $1. then save the value.
            shift
            USERHOME=$1
        ;;
        --force|-f )
            # set to 1 for later testing
            FORCE=1
        ;;
        -- )
            # set all the following arguments as files
            shift
            filelist="$filelist $@"
            break
        ;;
        -* )
            echo "Unrecognized option: $1"
            exit 1
        ;;
        * )
            filelist="$filelist $1"
        ;;
    esac

    shift

    if [ "$#" = "0" ]; then
        break
    fi
done

echo -n "Files:"

for f in $filelist ; do
    echo -e "\t$f"
done

echo "User home:" $USERHOME
echo "Forcing?" $FORCE

Here's some sample output:

annika@aziz:~/prog/argstest$ sh argstest.sh foo1 --home /home/annika foo2 -- --force foo3
Files:  foo1
    foo2
    --force
    foo3
User home: /home/annika
Not forcing.

As you can see, it works with long and short options, options that take values, and the "terminate option list" operator. All it needs is a man page.