30. Bash Shell - Expansions: brace, tilde, parameter
Contents
Linux provides us with some expansions for duplicate, print current user’s directory, and parameter operations.
Brace Expansion
We can use curly braces to output something similar to the screen:
|
|

Prints three similar words
Another example:
|
|

Prints three persons' names
Tilde Expansion
We can get our home directory through the tilde symbol:
|
|

Prints current user's home directory
We can also use the tilde symbol to see what files are in our home directory:
|
|

Prints our home directory's files
Parameter Expansion
This expansion has difference presentations:
|
|
|
|
|
|
If the param is null, use the word
The presentation of this expansion is as follows:
|
|
Let’s demonstrate:
|
|

Prints the value of MY_NAME_HYPHEN because it's not null
If the param is null, replace with word and use
The presentation of this expansion is as follows:
|
|
If there is a variable, use the value of the variable:
|
|

Prints the value of MY_NAME_EQUAL because it's not null
If there is no variable, use the word and assign the value to the variable:
|
|

Prints DONG and assign it to MY_NAME_EQUAL_NULL variable
If the param is not null, use the word
The presentation of this expansion is as follows:
|
|
If the variable exists, use the word:
|
|

Prints DONG because the MY_NAME_PLUS variable is not null
If the variable does not exist, nothing is used:
|
|

Prints nothing because the MY_NAME_PLUS_NULL variable is not null
Use a value as a variable name
The presentation of this expansion is as follows:
|
|
We can use the ! symbol to use the value of the variable as the name of another variable:
|
|

Prints the MY_FIRST_NAME variable's value with indirection feature
Delete the content before the first or the last appearance of a specified word and output the remaining content
The presentation of this expansion is as follows:
|
|
We can use the # symbol to delete the content before the specified word’s first or last appearance include the word itself, but this won’t change the value of the variable.
Delete to the first appearance:
|
|

Retrieves the variable's value before the first appearance removal and prints it after the deletion, this does not affect the variable's value.
Delete to the last appearance:
|
|

Retrieves the variable's value before the last appearance removal and prints it after the deletion, this does not affect the variable's value.
References 3.5.1 Brace Expansion, 3.5.2 Tilde Expansion, 3.5.3 Shell Parameter Expansion
Author Dong Chen
LastMod Sun Mar 3 2019