Code snippets for bash programming

Ever wonder how to figure out if if a variable/userinput is numeric? Here is a very elegant solution:


shopt -s extglob

i=-99
function is_integer {
[[ $1 = ?([+-])+([0-9]) ]]
}
is_integer $i && echo "yes" || echo "no"

Here is a a nice way to check options passed to a script:


while getopts "vhdl:" flag
do
case "$flag" in
d) DOIT=true;;
l) is_integer $OPTARG && LEVEL=$OPTARG || { echo "l needs numeric argument";exit;} ;;
v) DUMPOPTS="${DUMPOPTS}v" ;;
h) usage ;;
esac
done
# after this $* will contain everything BUT the options
shift $(($OPTIND - 1))

More information can be found at http://www.tldp.org/LDP/abs/html and http://www.faqs.org/docs/bashman/bashref.html