I saw in some of our scripts that there is a hyphen attached to a shell variable. For example:
if [ -z ${X-} ]
What does this hyphen symbol beside the variable do here. I cannot find any documentation online for this.
In man bash , at the end of the single-character options there is:- -- A -- signals the end of options and disables further option processing. Any arguments after the -- are treated as filenames and arguments.
dashes are not permitted in variable names in javascript (the parser will interpret them as a subtraction symbol) and thus are not permitted in environment variable names.
I believe that only letters, numbers, and underscore are allowed for bash variables. This is the case in many programming languages (javascript being an exception).
Shell (local) variables – Variables that affect only the current shell. In the C shell, a set of these shell variables have a special relationship to a corresponding set of environment variables. These shell variables are user, term, home, and path.
It's all explained in the Shell Parameter Expansion section of the manual:
${parameter:-word}
If
parameter
is unset or null, the expansion ofword
is substituted. Otherwise, the value ofparameter
is substituted.
Just before this there is:
Omitting the colon results in a test only for a parameter that is unset.
So:
${X-stuff}
expands to:
$X
if X
is setstuff
if X
is unset.Try it:
$ unset X
$ echo "${X-stuff}"
stuff
$ X=
$ echo "${X-stuff}"
$ X=hello
$ echo "${X-stuff}"
hello
$
Now your expansion is
${X-}
so you guess that it expands to the expansion of $X
if X
is set, and to the null string if X
is unset.
Why would you want to do this? to me it seems that this is a workaround the set -u
:
$ set -u
$ unset X
$ echo "$X"
bash: X: unbound variable
$ echo "${X-}"
$
Finally, your test
if [ -z "${X-}" ]
(note the quotes, they are mandatory) tests whether X
is nil (regardless of X
being set or not, even if set -u
is used).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With