1

In option string when using getopts, from http://wiki.bash-hackers.org/howto/getopts_tutorial

If the very first character of the option-string is a : (colon), which would normally be nonsense because there's no option letter preceding it, getopts switches to " silent error reporting mode". In productive scripts, this is usually what you want because it allows you to handle errors yourself without being disturbed by annoying messages.

I was wondering what the followings mean:

  • "silent error reporting mode"

  • "it allows you to handle errors yourself without being disturbed by annoying messages"?

Could you maybe give some examples?

3

If the very first character of optstring is a colon, getopts will not produce any diagnostic messages for missing option arguments or invalid options.

This could be useful if you really need to have more control over the diagnostic messages produced by your script or if you simply don't want anything to appear on the standard error stream if the user provides wonky command line options.

In silent reporting mode (with the initial :), if you want to alert the user of an invalid option, you will have to look for ? in the variable passed to getopts. Likewise, for missing option arguments, it's a :. These are the two errors usually handled by getopts itself, but to do your own error reporting to the user, you will need to catch these separately to be able to give the correct diagnostic message.

In non-silent reporting mode, getopts does its own error reporting on standard error and you just have to catch a * for "any error".

Compare these two examples:

#!/bin/bash

while getopts 'a:b:' opt; do
    case "$opt" in
        a) printf 'Got a: "%s"\n' "$OPTARG" ;;
        b) printf 'Got b: "%s"\n' "$OPTARG" ;;
        *) echo 'some kind of error' >&2
           exit 1
    esac
done
$ bash script.sh -a
script.sh: option requires an argument -- a
some kind of error
#!/bin/bash

while getopts ':a:b:' opt; do
    case "$opt" in
        a)  printf 'Got a: "%s"\n' "$OPTARG" ;;
        b)  printf 'Got b: "%s"\n' "$OPTARG" ;;
        :)  echo 'missing argument!' >&2
            exit 1 ;;
        \?) echo 'invalid option!' >&2
            exit 1
    esac
done
$ bash script.sh -a
missing argument!
1

Non-silent, getopts prints an error message:

$ bash -c 'getopts a opt' getopts_test -b
getopts_test: illegal option -- b

Silent, getopts doesn't print it by itself:

$ bash -c 'getopts :a opt' getopts_test -b
$

So with the colon for silent mode, we can print our own error in the script just the way we like it, instead of the fixed message:

#!/bin/bash
while getopts :a opt; do
    [[ $opt = "?" ]] && echo "Invalid option character '$OPTARG'" >&2;
done

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.