Parameter Expansion
Parameter Expansion
In Bash, parameter expansion is a mechanism for manipulating and handling the contents of variables. Through parameter expansion, you can get the value of a variable, modify the value of a variable, or provide a default value for an unset variable.
Shell Parameter Expansion
gnu.org
Variable Expansion
The most common way.
Default Value Expansion
Mark +
- var is undefined: returns an empty string.
- var is defined:
- is empty: returns DEFAULT.
- is not empty: returns DEFAULT.
This mark can be used to determine whether a variable is undefined.
Note
If ${var+defined}
is not used with double quotes, when an empty string is returned, the condition will become [ -n ]
, which is a valid condition, will not produce any errors, and its return value is true. Obviously this is unreasonable, so double quotes must be added.
Mark -
- var is undefined: returns DEFAULT.
- var is defined:
- is empty: returns var.
- is not empty: returns var.
var and DEFAULT values may be the same, so they cannot be used to determine whether var is defined.
Mark :+
- var is undefined: returns an empty string.
- var is defined:
- is empty: returns an empty string.
- is not empty: returns DEFAULT.
Mark :-
- var is undefined: returns DEFAULT.
- var is defined
- is empty: returns DEFAULT.
- is not empty: returns var.
Both of the above two examples will output foo.
Mark :=
- var is undefined: var=foo, returns var.
- var is defined
- is empty: var=foo, returns var.
- is not empty: returns var.
String Operations
Extract Substring
String Length
Remove Prefix
Remove the shortest match: use #
, pattern */
.
Remove the longest match: use ##
, pattern */
.
Remove Suffix
Remove the shortest match: use %
, pattern /*
.
Remove the longest match: use %%
, pattern /*
.