How do I handle switches in a shell script?-Collection of common programming errors

I wrote a script recently for work that was versatile and allowed for multiple kinds of switches in any order. I can’t disclose the full script for obvious legal reasons (not to mention I don’t have it with me at the moment), but here’s the meat of it.. you can put it in a subroutine and call it at the end of your script:

options () {

    if [ -n "$1" ]; then # test if any arguments passed - $1 will always exist
        while (( "$#" )); do  # process ALL arguments
            if [ "$1" = ^-t$ ]; then # -t short for "test"
                # do something here THEN shift the argument
                # shift removes it from $@ and reduces $# by
                # one if you supply no argument
                shift

            # we can also process multiple arguments at once
            elif [[ "$1" =~ ^--test=[:alnum:]{1,8}$ ]] && [[ "$2" =~ ^-t2$ ]] && [[ -n "$3" ]]; then # check for 3 arguments
                # do something more then remove them ALL from the arg list    
                shift 3
            else
                echo "No matching arguments!"
                echo "Usage: [script options list here]"
            fi
        done
    else
        echo "Usage: [script options list here]"
        exit 0
    fi
}

options "$@" # run options and loop through/process ALL arguments

I do recommend limiting your bash script to less than 400 lines/15k characters; my aforementioned script grew past this size and became greatly difficult to work on. I started rewriting it in Perl, which is much better suited for the task. Keep that in mind as you work on your scripts in bash. Bash is great for small scripts and oneliners, but anything more complex and you’re better off writing it in Perl.

Note, I haven’t test the above, so it probably doesn’t work, but you get the general idea from it.

Originally posted 2013-11-09 22:47:32.