Search⌘ K

Command Substitution

Explore the concept of command substitution in Bash scripting and how to embed the output of commands into scripts. Understand the two main methods—dollar-bracket and backtick—their usage, nesting techniques, and why the dollar-bracket method is preferred for clarity and manageability. This lesson equips you with essential skills to write dynamic and flexible Bash scripts.

How Important is this Lesson?

The contents of this lesson are vital if you intend to write or work on shell scripts.

Command Substitution Example

When writing bash scripts you often want to take the standard output of one command and ‘drop’ it into the script as though you had written that into it.

An example may help illustrate this idea. Type these commands:

Shell
hostname # 'hostname' outputs the name of the host
echo 'My hostname is: $(hostname)' # Single quotes do not call the hostname command
echo "My hostname is: $(hostname)" # Double quotes do, similar to variable dereferencing
Terminal 1
Terminal
Loading...

If those lines are placed in a script, it will output the hostname of the host the script is running on. This can make your script much more dynamic. You can set variables based on the output of commands, add debug, and so on, just as with any other programming language.

You may have noticed that if wrapped in single quotes, the special ...