Command Substitution

Learn how to use command substitution.

Example of command substitution

We can use the output of one command when invoking another command. This is handy when a program’s argument needs to be generated from another program’s output. We can do this with a feature called command substitution. We’ve already seen variable expansion with curly braces, like ${variable}, where the variable’s value is expanded. Command substitution works similarly. With command substitution, the output of the command replaces the command itself. To define a command substitution, we put the command in parentheses instead of curly braces. We saw an example of command substitution in Building Your Prompt when we used the tput command to emit color codes:

echo -e "$(tput setaf 6)Hello $(tput sgr0)world"

Get hands-on with 1200+ tech skills courses.