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
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:
Post a Comment