Parameter Expansion

What is parameter expansion?

It's much simpler than it sounds. It just means that in order to get the value out of some variable SOME_VAR, you just precede it with a $. Hence, $PWD will be replaced with the value of the PWD variable.

It is important to know that there are many more (useful) ways to have a variable's value substituted back in. We review zsh's mechanisms for expansion below. On the next page, we'll discuss many of the flags that can be used to change how zsh expands various paraneters.

Forms of Parameter Expansion

Form: ${VAR}

This is essentially an alternate form for $VAR. The value of VAR, if any, is substituted.

The braces are required if VAR is followed by a character that you don't want taken as part of its name...

  lyric[127]: NAME=Larry
  lyric[128]: echo $NAMED
  lyric[129]: echo ${NAME}D

Form: ${+VAR}

If VAR is set, 1 is returned. Otherwise, 0 is returned.

Form: ${VAR:-word}

This basically says that if VAR is set and non-null, then substitute in VAR's value like always. Otherwise, substitute in word.

This form of expansion is useful for setting defaults.

Form: ${VAR:=word}

If VAR is unset or is null then set it to word. Then, return word.

Form: ${VAR:?word}

If VAR is set and is non-null, then return its value. Otherwise, print word and exit the current command or script. (If you leave out word, a standard message will be displayed.)

Form: ${VAR:+word}

If VAR is set and non-null, return word. Otherwise, reuturn nothing.


Many expressions above mention a colon. If you leave out the colon, zsh checks to see if the variable is set. zsh won't care if it's null or not.

Form: ${VAR::=word}

Set VAR to word. The value of the parameter is then returned. This is similar to :=, except that it forces VAR to word.


If the pattern matches the beginning of the value of name, then substitute the value of name with the matched portion deleted. If the pattern does not match the beginning of the value, just substitute the value of name.

In the first form, the smallest matching pattern is preferred. (A non-greedy match). In the second form, the largest matching pattern is preferred. (A greedy match). (1)


Exactly like the previous expansion, except that matching is done on the end of the value, not the beginning.

Form: ${name:#pattern}

If the pattern matches the value of name, then substitute the empty string. Otherwise, just substitute the value of name.

If name is an array, (1) the matched array elements are removed. Ise the (M) flag to remove the non-matched elements.

Form: ${#sub}

sub can be any of the above substitutions. The length in characters of the result will be returned instead of the result itself. If sub is an array expression, substitute the number of elements of the result.