Skip to content
Advertisement

zsh parameter expansion syntax: combining default value and conversion to upper case

In a zsh script,

echo ${X:-4711}

outputs the value of the variable X, or 4711 if there is none.

echo ${X:u}

outputs the value of the variable X, converted to upper case.

I wonder, whether there is a way to combine the two, i.e. to have the effect of

tmp=${X:-4711}
echo $X:u

without introducing an auxiliary variable.

Advertisement

Answer

$ echo ${${X:-4711}:u}
4711
$ X=hello
$ echo ${${X:-4711}:u}
HELLO

From man zshexpn:

If  a  `${...}`  type  parameter expression or a `$(...)` type command
substitution is used in place of name above, it is expanded first and
the result is used as if it were the value of name.  Thus it is possible
to perform nested operations:  `${${foo#head}%tail}` substitutes the value
of `$foo` with both 'head' and 'tail' deleted.
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement