Search code examples
linuxbashshellgetopts

shell getopts parameters collection issue


I have below code in my shell script.

show_help()
{
    cat <<EOF
Usage: ${0##*/} [-h help] [-g GATEWAY_HOSTID] [-t TIMEZONE]

         -h                     display this help and exit
         -g GATEWAY_HOSTID      zabbix gateway identifier (e.g. '20225')
         -t Time Zone          TimeZone against which you want to test
EOF
}

OPTIND=1

while getopts "g:h:t" opt; do
  case "$opt" in
    h)
      show_help
      exit 0
      ;;
    g)
      gateway_hostid=$OPTARG
      ;;
    t)
      timezone=$OPTARG
      ;;
    esac
done

shift $((OPTIND-1))

if [[ ! $timezone ]]; then
    timezone="UTC"
fi

if [[ ! $gateway_hostid ]]; then
    echo "hostid is missing!!! Exiting now."
    exit
fi

When I execute script it only takes parameter gateway_hostid and ignores timezone parameter. I am not sure what I am doing wrong here. Also it doesn't show help function as well. Can someone help. below is the syntax for calling script.

./script_name.sh -g 20225 -t Europe/Zurich
./script_name.sh -g 20225 -t CEST

Solution

  • Your problem is with the optstring. You're specifying h: which means that -h requires an option. You are also specifying t without a : meaning t does not expect an option.

    The optstring to have g and t take options and h not need one is hg:t: