bashshellcommand-line-interfacegetopts

An example of how to use getopts in bash


I want to call myscript file in this way:

$ ./myscript -s 45 -p any_string

or

$ ./myscript -h  #should display help
$ ./myscript     #should display help

My requirements are:

So far, I tried this code:

#!/bin/bash
while getopts "h:s:" arg; do
  case $arg in
    h)
      echo "usage" 
      ;;
    s)
      strength=$OPTARG
      echo $strength
      ;;
  esac
done

But with that code I get errors. How to do it with Bash and getopt?


Solution

  • #!/bin/bash
    
    usage() { echo "Usage: $0 [-s <45|90>] [-p <string>]" 1>&2; exit 1; }
    
    while getopts ":s:p:" o; do
        case "${o}" in
            s)
                s=${OPTARG}
                ((s == 45 || s == 90)) || usage
                ;;
            p)
                p=${OPTARG}
                ;;
            *)
                usage
                ;;
        esac
    done
    shift $((OPTIND-1))
    
    if [ -z "${s}" ] || [ -z "${p}" ]; then
        usage
    fi
    
    echo "s = ${s}"
    echo "p = ${p}"
    

    Example runs:

    $ ./myscript.sh
    Usage: ./myscript.sh [-s <45|90>] [-p <string>]
    
    $ ./myscript.sh -h
    Usage: ./myscript.sh [-s <45|90>] [-p <string>]
    
    $ ./myscript.sh -s "" -p ""
    Usage: ./myscript.sh [-s <45|90>] [-p <string>]
    
    $ ./myscript.sh -s 10 -p foo
    Usage: ./myscript.sh [-s <45|90>] [-p <string>]
    
    $ ./myscript.sh -s 45 -p foo
    s = 45
    p = foo
    
    $ ./myscript.sh -s 90 -p bar
    s = 90
    p = bar