--- layout: page category-page: scripts category-title: Scripting tags: parameter expansion brace variable check condition empty exists author: Marco Tereh title: Parameter expansion previous-page: pages/scripts/special_variables.html next-page: pages/scripts/arrays.html --- There are some special operations that can be performed on variables and strings called parameter expansions. The general syntax for all parameter expansions is this one: {% highlight bash %} ${CODE_HERE} {% endhighlight %} Depending on what you want to do with your variable, the code that goes inside the braces differs.

{% highlight bash %} ${VARIABLE:-DEFAULT_VALUE} {% endhighlight %} If the variable VARIABLE exists and has a value (i.e. it is not null), this is equal to the value of VARIABLE. Otherwise, it is equal to DEFAULT_VALUE.
Example: echo "First name: ${firstname:-John}";

{% highlight bash %} ${VARIABLE:=DEFAULT_VALUE} {% endhighlight %} If the variable VARIABLE exists and has a value, this is equal to the value of VARIABLE. Otherwise, it sets the variable to DEFAULT_VALUE and is equal to it.
Example: echo "Last name: ${lastname:=Doe}";

{% highlight bash %} ${VARIABLE:?ERR_VALUE} {% endhighlight %} If the variable VARIABLE exists and has a value, this is equal to the value of VARIABLE. Otherwise, it prints ERR_VALUE to STDERR and exits (meaning nothing else will be executed after this).
Example: currdate=${date:?Operation failed: date unknown};

{% highlight bash %} ${VARIABLE:+VALUE} {% endhighlight %} If the variable VARIABLE exists and has a value, this is equal to VALUE. Otherwise, this has no effect.
Example: echo -e "reading from address $read.${write:+\nWARNING: read and write set at the same time}";

All of these can also be written without the colon, in which case their meaning changes to "If the variable VARIABLE exists at all (even if it is null), this is ..."


{% highlight bash %} ${VARIABLE: NUMBER} {% endhighlight %} This is equal to the substring of the value of VARIABLE, starting at the character with (0-based) index NUMBER
If NUMBER is negative, the substring starts NUMBER characters before the end of the string.
Example: lastname=${fullname:$firstnamelength};

{% highlight bash %} ${VARIABLE: FROM:LENGTH} {% endhighlight %} This is equal to the substring of the value of VARIABLE, starting at the character with (0-based) index FROM with length LENGTH
If FROM is negative, the substring starts FROM characters before the end of the string.
Example: lastname=${middlename:$firstnamelength:$middlenamelength};

{% highlight bash %} ${#VARIABLE} {% endhighlight %} This is equal to the length of the value of VARIABLE
Example: echo "your name has ${#name} characters";

Paremeter expansions can also be nested, like this: {% highlight bash %} ${input:?${INVALID_INPUT_ERR_MSG:-An unknown error occurred}} {% endhighlight %}
Further reading: the bash reference manual