whoan
whoan

Reputation: 8531

Parameter expansion without colon (default value to empty string) in a condition

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-}" ]

Upvotes: 0

Views: 251

Answers (2)

chepner
chepner

Reputation: 531808

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 ]]

Upvotes: 1

fumiyas
fumiyas

Reputation: 367

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

Upvotes: 1

Related Questions