I have this script that I have cobbled together from bits of lore I've gleaned from googling:

#!/usr/bin/env bash

usage() {
    declare -r script_name=$(basename "$0")
    echo """
"${script_name}" [option] <name>

    -host <foo.com|bar.com|baz.com|...>
    -accountId <001123456789|002123456789|...>

main() {
    if [[ $# -eq 0 ]]; then
        exit 1

OPTIONS=$(getopt -o '' -l help,host,accountId -- "$@")

eval set -- "$OPTIONS"

while true
    case $1 in
    -help) usage
           exit 0
    -accountId) ACCOUNTID=$2; shift 2;;
    -host) HOST=$2 shift 2;;
    --) shift ; break ;;

echo host: $HOST, accountId: $ACCOUNTID


main "$@"

Here's what it outputs:

$ . test.sh -help
host: , accountId:

$ . test.sh -host foo.com -accountId 001123456789
host: , accountId:

What have I done wrong?

  • A long option is usually preceded by --, as in --accountId. – Kusalananda Apr 12 at 15:57

Minor bug, there should be a ; after the HOST=$2

If you want to use a single dash in front of long options, you can add the -a option to getopt.

Also as the host and accountId have required options, they should be followed by a :

OPTIONS=$( getopt -a -o '' -l help,host:,accountId: -- "$@" )

(camelCase isn't the best for options, how about just accountid instead of accountId)

And I generally prefer to give both long and short options, so would use:

OPTIONS=$( getopt -a -o 'h:a:' -l help,host:,accountId: -- "$@" )


-a|--accountId) ACCOUNTID=$2; shift 2;;
-h|--host) HOST=$2; shift 2;;

You should also check the result code from getopt, if the options are wrong you don't want to continue:

So after the OPTIONS=$(... line add the following:

if [[ $? -ne 0 ]] ; then
    usage ; exit 1

And on a minor aside, if the usage is being displayed, you probably always want to exit, so why not put the exit 1 at the end of usage, then you could use:

[[ $# -eq 0 ]] && usage
[[ $? -ne 0 ]] && usage
--help) usage;;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.