Bash Parameter and Variable Expansion: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 65: Line 65:
{{Internal|envsubst#Overview|envsubst}}
{{Internal|envsubst#Overview|envsubst}}


==String Length==
=String Length=


The length of a variable's value:
The length of a variable's value:

Revision as of 21:20, 18 September 2019

Internal

Overview

A dollar sign ($) that is NOT followed by an open parenthesis initiates parameter or variable expansion, which is a particular case of command line expansion. The simplest case of parameter expansion is retrieving the parameter value: the associated value is retrieved by prefixing the parameter's number, character or name with $ or enclosing it in ${...}.

Parameters and variables are not expanded if the string they are included in are enclosed within single quotes or if the leading dollar sign is escaped. Parameters and variables are expanded if the string they are included in is enclosed within double quotes.

Difference between $ and ${...}

TODO

Expand to a Default Value

http://wiki.bash-hackers.org/syntax/pe#use_a_default_value
${var:-alternative}

The :- form : if the variable 'var' referred in the expression was not defined, or it is the empty string, the expression expands the alternative.

${var-alternative}

The - form: if the colon is omitted, the expression is expanded to the alternative value only if the variable is not defined, not when it was empty.

Assign a Default Value

http://wiki.bash-hackers.org/syntax/pe#assign_a_default_value
 ${var:=word}
${var=word}

This expression works like expansion to a default value, but the word is not only expanded, but also assigned to the variable, if it was unset or null. The first form work if the variable is unset or an empty string, the second only if the parameter was unset.

Use an Alternate Value

http://wiki.bash-hackers.org/syntax/pe#use_an_alternate_value
${var:+alternative}

This form expands to nothing if the parameter is unset or empty.

${var+alternative}

This form expands to nothing if the variable is unset, and to the alternative if the variable is empty.

Variable Expansion in an Arbitrary File

If an arbitrary text file contains environment variable declarations, they can be expanded with envsubst. No other shell command line expansions will be performed. More details:

envsubst

String Length

The length of a variable's value:

${#var}