I've come across this piece of code from here:
#!/bin/bash
...
if [[ "${1-}" =~ ^-*h(elp)?$ ]]; then
echo "Usage..."
exit
fi
I understand what this does is print the usage information when any argument like -h
, --help
, -help
, -------help
is passed.
But why "${1-}"
and not just "${1}"
? What does the hyphen do?
At first I thought it could mean any argument from the position 1 onward. I tried it and no, it wasn't that.
Then I thought it could be a typo and the author meant "${1-9}"
to allow all number positions. Again, it didn't work, it isn't even valid code.
"${a:-b}"
(with:-
) instead of just"${a-b}"
. I've tried finding the meaning in the answers but couldn't. Does it make a big difference? – xtropicalsoothing Feb 10 '23 at 10:23${a:-b}
expands tob
ifa
is either unset or empty,${a-b}
expands tob
ifa
is unset. Since the default in${1-}
is empty,${1-}
and${1:-}
have the same effect. – Stephen Kitt Feb 10 '23 at 10:35