Friday, May 25, 2012

Simple way to use getopts

Most getopts examples show complex case switches in a while loop and complicated logic to set defaults.

In general, getopts is very simple to use:


#!/bin/bash
# example options -t and -a with args and -x with no args
C=0
while getopts xt:a: arg
do
    # remove punctuations to prevent shell injection
    V=$(echo $OPTARG | perl -lpe 's/[^a-zA-Z0-9_. ]/_/gs')
    eval "$arg='${V:-true}'"
    if [ -n "$OPTARG" ]; then C=$[C+2] ; else  C=$[C+1] ; fi
done
shift $C
echo $@  # args after params

# in case option was not passed set defaults
t=${t:-template}


#err check/usage
if [ -z "$a" ] 
then 
    echo Usage: $0 [-x] [-t text] -a address; exit 1; 
fi


# use it!
echo T is $t and A is $a and X is $x

No comments: