0

I know the difference between ${var:-word} and ${var-word}, but I don't see the purpose of using a default value in this condition:

[ -z "${NVM_PROFILE-}" ]
  • Why is an empty default value needed there?
  • Is it something related to compatibility with other shells (zsh)?
whoan
  • 8,143
  • 4
  • 39
  • 48
  • That code makes no sense to me. If the test succeeds, it goes ahead and uses a (potentially unset) `${NVM_PROFILE}` anyway. If the test doesn't succeed, it still uses `${NVM_PROFILE-}` in the `else` branch, even though `$NVM_PROFILE` must be set at that point. – melpomene May 02 '18 at 05:53

2 Answers2

1

I like set -u.

$ sh -c '[ -z "NVM_PROFILE" ] && echo empty'
empty
$ sh -c 'set -u; [ -z "$NVM_PROFILE" ] && echo empty'
sh: NVM_PROFILE: unbound variable
$ sh -c 'set -u; [ -z "${NVM_PROFILE-}" ] && echo empty'
empty
fumiyas
  • 367
  • 3
  • 11
1

If the nounset option is enabled with set -u or set -o nounset, [ -z "$NVM_PROFILE" ] would result in an error if NVM_PROFILE isn't set. Using - or :- to explicitly expand the unset variable to an empty string avoids that error.

An alternative to using set -u is to check explicitly if the variable is set. (This works in zsh and bash.)

[[ ! -v NVM_PROFILE || -z $NVM_PROFILE ]]
chepner
  • 497,756
  • 71
  • 530
  • 681