Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

shell

zsh

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.

like image 444
rugk Avatar asked Mar 13 '26 06:03

rugk


2 Answers

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.

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
like image 31
metamorphling Avatar answered Mar 16 '26 03:03

metamorphling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!