Using getopts

Hi. Can somebody please show me an example of how to use getopts to assign a variable if it's been passed into the script but to set a default if no value has been passed in? And also how to handle a param with multiple values ... so a sub parse (can I use a function for this?)?

Here's my code that needs to be tweaked:
E.g.

typeset flags_args=''
for arg; do
    case $arg in
        -user )  flags_args="${flags_args} -u" ;;
        -exception ) flags_args="${flags_args} -e" ;;
        -optional ) flags_args="${flags_args} -o" ;;
        * )       flags_args="${flags_args} $arg" ;;
    esac
done
set -- ${flags_args}

while getopts :u:e:o: args; do
    case $args in
        u) typeset USER="$OPTARG" ;;
        e) typeset EXCEPTION="$OPTARG" ;;
        o) typeset OPTIONAL="$OPTARG" ;;
        *) usage ;;
    esac
done
shift $((OPTIND-1));

how can I make 'user' a required param, 'exception' an optional param but sets a default value if not specified, and 'optional' just an optional param but with multiple values?
Many thanks.

You can set user as mandatory by testing if it's set (although you may want to use another variable name (USER is a shell variable)):

i.e.

while getops ...; do
  ...
done
...
if [ -z "$USR" ]; then
  usage
  exit 1
fi

EXCEPTION=${EXCEPTION:-some_default} # set default to 'some_default' if not given
2 Likes