Linux Shell Expansions: $(), ${}, Globbing, and Brace Expansion
Linux allows the use of Shell expansions, useful for using command output in variables. The result can be used for processing, generally in a shell script.
The symbols that allow shell expansion are:
- $( ) - dollar sign with parentheses.
- ` ` - backticks.
- ${ } - dollar sign with curly braces.
The expansions $( ) and ` ` do the same thing. However it is recommended to use $( ) because it is more readable, and less prone to errors when copying a script.
To use the expansion, simply place the desired command between the parentheses or between the backticks.
Command Output Expansion $( ) and ``
Example of command output expansion:
#!/bin/bashHOJE=$(date "+%d/%m")ID=`id -un`echo "Bom dia $ID, hoje é $HOJE"
When running this small script, you can see that the output of the date and id commands were directed to the HOJE and ID variables that could be used later in the script:
$ ./expansao
Bom dia uira, hoje é 12/01
To use command expansions, it is common to also use a variable, to store the result of the command execution.
${ } Expansion
The ${ } expansion allows delimiting the name of a variable, and even making substitutions.
Example:
$ bicho="gato"$ echo $bichogato
If you want to use the content of the variable together with text, it will not work:
$ echo "os $bichos foram passear"os foram passear
For this to work, you must use the variable name between ${ }:
$ echo "os ${bicho}s foram passear"os gatos foram passear
It is also possible to make substitutions, using the common slash "/", searching for an occurrence and replacing it with another:
$ echo "O ${bicho/gato/cachorro} latiu"
O cachorro latiu
Conclusion
Shell expansions are powerful for storing the result of a command in a variable. This allows you to process the results of commands intelligently to create procedures or handle data.
Learn much more about Linux in our online course. You can enroll here. If you already have an account, or want to create one, just log in or create your user here.
Did you like it? Share
That was just one piece. The course teaches the whole path — from your first command to exam day.