Skip to content

Shell expansions on Linux

Linux allows the use of Shell expansions, useful for using the output of commands in variables. The result can be used for processing, usually in a shell script.

The symbols that allow shell expansion are:

  • $ () - dollar symbol with parentheses.
  • - phrases.
  • $ {} - dollar symbol with keys.

The $ () and expansions do the same thing. However, it is recommended to use the $ () because it is more readable and less susceptible to errors when copying a script.

To use the expansion, simply place the desired command between the brackets or between the phrases.

Command Output Expansion $ () and “

Example of expanding command output:

#! /bin/bash

TODAY=$ (date “+%d/%m”)
ID=ID -un
echo “Good morning $ID, today is $TODAY” When running this short script, it can be seen that the output of the date and id commands were directed to the TODAY and ID variables that could be used later in the script:

$. /expansion
Good morning Uira, today is 12/01

To use command expansions, it is common to also use a variable to store the result of the execution of the command.

Expansion $ {}

The $ {} expansion allows you to delimit the name of a variable, and even make substitutions.

Example:

$ bug="cat” $ echo $cat bug

If you want to use the variable content together with a text, it won’t work:

$ echo “the $animals went for a walk” they went for a walk

For this to work, you must use the variable name between $ {}:

$ echo “the $ {animals} s went for a walk” the cats went for a walk

It is also possible to make substitutions, using the common bar “/”, searching for one instance and replacing it with another:

$ echo “The $ {animal/cat/dog} barked”
The dog barked

Conclusion

Shell expansions are powerful for storing the result of a command in a variable. This allows you to process the results of the commands intelligently to create procedures or process the data.

Learn much more about Linux in our online course. You can register 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