Ranting, Technically Speaking

July 30, 2007

Processing Arguments in BASH

Filed under: HOWTO — archangel @ 1:40 pm

There are many ways to skin a cat, but in a bash script, this is probably the “most right” way to processes command line arguments:

#!/bin/bash

while getopts vf: opt ; do
        case "$opt" in
          v) echo "verbose set" ;;
          f) echo "f: $OPTARG" ;;
         \\?) echo "Error: unknown flag" >&2 ;;
        esac
done

shift `expr $OPTIND - 1`

Basically, you run “getopts” giving it a “parameter string” and a variable name. The parameter string is a list of letters you want to pull arguments from and each one that takes an argument itself is followed by a colon (:).

Loop through the arguments as above, and then use “shift” and the “OPTIND” to shift off all the arguments that were processed, leaving only the “regular” arguments, e.g. take out all the “-v” and such but leave the list of file names.

Props: SHELLdorado

1 Comment

  1. While on the topic of bash scripting, when creating functions, create them as “myfunction () { … }” and not “function myfunction { … }”. The former is more portable, the latter, I don’t even know why it exists. Presumably some historical reason.

    Comment by archangel — July 30, 2007 @ 1:43 pm

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress