3

what is the easiest, most straight forward, way to use getopts in bash script.

if i have a script called: myscript and it CAN take the the arguments: -p -r -s -x

if argument x then exit
if argument p then echo "port 10"
if argument s then add 2+2
if argument r then echo env 

This is a hypothetical script but I would just like to see an example of how this would be done.

stackoverflow
  • 18,348
  • 50
  • 129
  • 196
  • possible duplicate of [Using getopts in bash shell script to get long and short command line options](http://stackoverflow.com/questions/402377/using-getopts-in-bash-shell-script-to-get-long-and-short-command-line-options) –  Oct 04 '11 at 13:46
  • I seen it, didnt help me. Thanks for pointing that out though – stackoverflow Oct 04 '11 at 14:12

2 Answers2

10
while getopts :xpsr opt; do
   case $opt in
     x ) exit                                ;;
     p ) echo port 10                        ;;
     s ) (( 2 + 2 ))                         ;;
     r ) echo env                            ;;
    \? ) echo "${0##*/}" [ -xpsr ]; exit 1   ;;
  esac
done
Dimitre Radoulov
  • 27,252
  • 4
  • 40
  • 48
3
usage()
{
    echo "Usage: $0 [-o <offset>] [-h];"
    exit 0;
}

# -o (offset) need a value
# -h prints help
offset=0    # 0 is default offset

while getopts o:s opt
do
    case "$opt" in
    d)  offset="$OPTARG";; # changing offset
    s)  usage              # calls function "usage"
    \?) echo "$OPTARG is an unknown option"
        exit 1;; # all other options
    esac
done

shift $((OPTIND-1))
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Arnaud F.
  • 8,252
  • 11
  • 53
  • 102