Question

I have a new RHEL6 machine and I'm trying to run a script to generate some output. The script uses getopts which I've never used in the past. This should have worked on other machines but is my first time trying it. Below is the beginning of the script. Is there anything wrong with the syntax? When I try to output the variables it displays nothing:

#! /bin/sh

while getopts "h:u:g:o:e:y:bf" c
 do
     case "$c" in
       u)         USER=$OPTARG;;
       g)         GROUP=$OPTARG;;
       o)         OUT=$OPTARG;;
       b)         BATCH=1;;
       f)         FORCE=1;;
       h)         FQDN=$OPTARG;;
       e)         ENTITYID=$OPTARG;;
       y)         YEARS=$OPTARG;;
       \?)        echo "keygen [-o output directory (default .)] [-u username to own keypair] [-g owning groupname] [-h hostname for cert] [-y years to issue cert] [-e entityID to embed in cert]"
                  exit 1;;
     esac
 done
echo $FQDN

The echo displays a blank line.

Was it helpful?

Solution

You can't use question mark with the bash getopts (you also can't use the colon). In the case of question mark, getopts sets the value of the argument ($c in your case) to a question mark when the end of options has been encountered. It also uses question mark and colon as the value for the argument name when there's an error (specifically, ? is used when an invalid option is encountered or when in non-silent mode and a required option is not provided; colon is used in silent mode when a required option is not provided). In those error cases, OPTARG contains the offending argument. This is how POSIX getopts works as well.

The KSH getopts behaves differently, but it also excludes ? : (as well as - [ ] and only allowing # as the first option). It does, however, show a usage message when you provide -?. Basically, don't use -? with shell getopts. :)

Typically, I write a small function called "usage" and call it from both *) and by checking $? immediately after the case statement for non-zero value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top