3 ways to parse arguments with bash scripts
Parse with getopts (bash-builtin)
while getopts "fhm" OPTION; do
case $OPTION in
f) FORCE=1 ;;
h) print_help; exit ;;
m) BASE="MM" ;;
*) echo "Unknown Argument $OPTION given"; exit 1;;
esac
done
Parse in ‘while’-loop
#!/bin/bash
while [ "$1" ]; do
optarg=""
opt=""
case "$1" in
-*=*)
opt=`echo "$1" | sed 's/=.*//'`
optarg=`echo "$1" | sed 's/[-_a-zA-Z0-9]*=//'`
;;
*)
opt=$1
;;
esac
case $opt in
-u)
shift; # shift the '-u'
MYUSER=$1
shift; # shift the val
;;
--user)
MYUSER=$optarg;
shift; # shift the '--user=val'
;;
-h|*)
echo "my help text "
exit 1
;;
esac
done
echo "\$MYUSER = $MYUSER"
echo "\$Q = $Q"
exit 0
Parse in ‘select’-loop
select opt in $@; do
if [ "$opt" = "Quit" ]; then
echo done
exit
elif [ "$opt" = "Hello" ]; then
echo Hello World
else
clear
echo bad option
fi
done