rugk
rugk

Reputation: 5573

How to parse a question mark as parameter in zsh/shell script?

The parameters --help, -h or -? are common for showing information about how to use a program/script.

So one may parse them like this:

#!/bin/sh
# […]
case "$1" in
    '' ) # no parameters
        echo "something missing here"
    --help|-?|-h ) # show help message
        show_help
        exit
        ;;
    *)
        # do something else…
        ;;
esac

Passing --help and -h works. However when I pass -? to it, it fails with the error:

zsh: no matches found: -?

Now even when using a simple if loop it fails:

if [ "$1" = "-?" ]; then
    show_help
    exit
fi

Note that passing "-?" or '-?' works, but that is silly and nobody does it.

I also could not reproduce this in bash, only in zsh.

Upvotes: 3

Views: 2562

Answers (2)

user2404501
user2404501

Reputation:

An example of a program with a -? help option is less. A long time ago, if you ran it with no arguments, it would say

Missing filename ("less -\?" for help)

Because -? by itself was fragile. In the Bourne/Korn/POSIX-compatible shells, it has different behavior depending on whether a file exists in the current directory with 2 characters in its name and - as the first character.

It doesn't say that any more, because -\? was a silly help option. Now it says

Missing filename ("less --help" for help)

(And surely it would have gone with -h if that hadn't been taken for some other purpose)

less -\? still displays the help, like it always did, but nobody is encouraged to use it.

Follow this example.

Upvotes: 4

metamorphling
metamorphling

Reputation: 389

Probably, question mark symbol resolves to return value of the last executed command. Anyway, guarding it with backslash "\" should prevent interpreting it as anything else.

#!/bin/zsh
# […]
case "$1" in
    '' ) # no parameters
        echo "something missing here"
    ;;
    --help|-\?|-h ) # show help message
        show_help
        exit
        ;;
    *)
        # do something else…
        ;;
esac

Upvotes: 1

Related Questions