0

In the traditional Bourne Shell (sh), if one wants to make sure that, at some point in the script, a variable has been set and at least it has some specific default value, one can use this construct:

: "${VAR:=defaultValue}"

What would be the equivalent for a Zsh script?

Thanks.

Edit: I mean, in case there is a Zsh specific way for doing this. Instead of just doing the true command (:).

Edit2: Rightfully quoting the parameter expansion. See Stéphane Chazelas' answer.

  • The ${parameter:=[word]} syntax is defined by POSIX, is there any reason you don't want to use that? – terdon May 14 '21 at 17:30
  • Oh, no reason at all for not using ${var:=value}, I am fine with it. Just asking in case there is a Zsh-specific way for when all one wants to do is the paramenter expansion by itself (not as a side effect of executing a command). In sh one uses the ':' command for this. And it seems it is the same for zsh and the rest of shells (thanks @Stéphane Chazelas) – José Otero May 14 '21 at 18:16

1 Answers1

8

Actually,

: ${VAR:=defaultValue}

is correct in zsh (provided you've not enabled the globsubst option), but not in other shells. In other Bourne-like shells, that would constitute a denial of service vulnerability unless you enable the noglob options as seen at Security implications of forgetting to quote a variable in bash/POSIX shells.

In those, you'd need

: "${VAR:=defaultValue}"

zsh does support those Bourne operators and even introduces a couple of its own in that same vein:

  • ${VAR::=value} unconditionally assigns value to the variable (and expand to the result). That is useful in zsh as it can be combined with other parameter expansion operator or flags.
  • ${:-value} (i.e. with VAR omitted) expands to value. Again useful when combined with other operators.

Another option here is to do:

VAR=${VAR:-defaultValue}

Which would be OK in zsh and all other Bourne-like shells and may convey the meaning more clearly.

  • Thank you for the link "Security implications of forgetting to quote a variable in bash/POSIX shells". Very, VERY, enlightening. – José Otero May 14 '21 at 18:43