A stackoverflow post has a template for handling command line arguments.

Does the test [ $# == 0 ] mean that a bash script shouldn't be run without any argument? As a template, I think that scripts generally do not necessarily require any argument.

In the case statement, how different are the two cases *) and "?") ? They seem the same.

# --- Options processing -------------------------------------------
if [ $# == 0 ] ; then
    echo $USAGE
    exit 1;

while getopts ":i:vh" optname
    case "$optname" in
        echo "Version $VERSION"
        exit 0;
        echo "-i argument: $OPTARG"
        echo $USAGE
        exit 0;
        echo "Unknown option $OPTARG"
        exit 0;
        echo "No argument value for option $OPTARG"
        exit 0;
        echo "Unknown error while processing options"
        exit 0;

shift $(($OPTIND - 1))

  • There are two questions here. Nov 22, 2018 at 12:43

2 Answers 2


This script requires at least one arg, if not it displays usage info. It should do echo $USAGE >&2 as this is an error. Other scripts may work with zero arguments, so you will have to modify. Just as some don't take the argument i.

"?", vs *

Yes they are different:

  • "?" says to case to look for a ?. This is what getopts returns when it finds an option that it does not expect (invalid option).
  • * says to case, do this is you find no other match. This should not happen, but it may. It probably indicates a bug in getopts, or more likely your program (see defensive programming).

They should be the same.

However that code has its own share of problems:

  • failure to quote arithmetic expansions; should be shift "$(($OPTIND - 1))"
  • usage of the unportable == operator
  • error messages written to stdout
  • exit with 0 (success) status in case of error
  • failure to quote variables; should be "$#" and echo "$USAGE"
  • bad placement of the if-no-arguments check; it should be after the getopts loop, in order to not be fooled by script --
  • useless quoting of v, h, i and :i:vh

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .