Bash Command Substitution
Command substitution runs a command and captures its output as a value. The captured text can be stored in a variable with $( ) around the command.
Capture the output of echo
The echo command runs inside $( ) and its output is stored. Printing the variable shows the stored word.
word=$(echo "sunny")
echo "The word is $word"Capture a folder listing
The script builds a project folder with two folders inside it. The ls output is captured and then printed from the variable.
mkdir project
cd project
mkdir docs
mkdir photos
names=$(ls)
echo "Folders found:"
echo "$names"Capture output from a function
The function echoes one number built with arithmetic. The call sits inside $( ), so the number lands in the variable.
get_total() {
echo $((4 + 5))
}
total=$(get_total)
echo "The total is $total"Example
mkdir library
cd library
mkdir books
mkdir games
mkdir music
folders=$(ls)
echo "The library holds these folders:"
echo "$folders"
echo "The listing came from a variable"Key points
- The $( ) form runs the command written inside it.
- The output of that command replaces the whole $( ) part.
- The result is often stored in a variable with an assignment.
- Captured line breaks are kept when the variable is printed in quotes.
- A function call can also sit inside $( ).
- Capturing output stores it instead of printing it right away.
In this example, three folders are created inside a new library folder. The ls command lists them, and $( ) stores the list in a variable. The echo commands then print a heading, the saved list, and a closing line.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does files=$(ls) store in the files variable?