1

I'm trying to get the following as valid calls of my script:

sh name.sh -l -a
sh name.sh -l

This is the code I have so far using getopts, where -a is an required argument:

default="no"

echo "Initial parameters. 

while getopts ":l:a:" o; do
    case "${o}" in
        l)
            ...;;
        a)
            a+=(${OPTARG})
            IFS=',' read -a myarray <<< "$a"
            default="yes"
            ;;
        :)
            echo "Missing option argument for -$OPTARG" >&2; exit 1;;
        *)
            usage;;
    esac
done
shift $((OPTIND-1))

if [ -z "${l}" ] || [ -z "${a}" ] ; then
    usage
fi

I just need to know how to set in getopts the optional flag -a with it's argument. Thanks:)

Momina
  • 41
  • 1
  • 8
  • Possible duplicate of [Optional option argument with getopts](http://stackoverflow.com/questions/11517139/optional-option-argument-with-getopts) – qzb Sep 03 '16 at 13:34
  • @qzb no, I'm using getopts and don't wanna do without it. – Momina Sep 03 '16 at 18:05

1 Answers1

1

As far as I know, getopts has no support for optional option-arguments. You can workaround this by handling option-argument by yourself:

#!/bin/bash

while getopts "x" o; do
  case "${o}" in
    x)
      OPTARG=${!OPTIND}

      if [ "${OPTARG:0:1}" == "-" ] || [ "$#" -lt "$OPTIND" ]; then
        OPTARG="DEFAULT"
      else
        OPTIND=$(( $OPTIND + 1 ))
      fi

      echo $OPTARG
      ;;
  esac
done
qzb
  • 8,163
  • 3
  • 21
  • 27