What does the $( ) syntax do in Bash?

Linux School Tech
2 min readJan 25, 2024
Generated By: Adobe Filefly AI

The $() syntax in Bash is used for command substitution. It allows you to execute a command and substitute its output in place of the $() expression. This is useful when you want to use the output of a command as an argument for another command or assign it to a variable.

Here is an example of basic command substitution:

date=$(date)
echo "Today's date is $date"

In this example, the date command is executed and its output is stored in the date variable. Then, the value of the date variable is printed.

Command substitution can also be used within loops. Here is an example:

for file in $(ls)
do
echo "Processing file: $file"
done

In this example, the ls command is executed and its output (a list of files in the current directory) is used as the input for the for loop.

You can also use command substitution directly within a command. For instance, consider the following example:

echo "The current date is $(date)."

Here, the $(date) command is executed, and its output (the current date) is substituted into the echo command. The result will be a message that includes the current date.

Thus:

  1. When you enclose a command within $( ), Bash executes that command and captures its output.
  2. The output of the command is then substituted into the original command or assigned to a variable.

Can $( ) be nested within other commands or variables?

$( ) can indeed be nested within other commands or variables. This is often referred to as nested command substitution. It allows the output of one command to be used as an argument for another command. This technique can help you avoid unnecessary intermediate files, write more concise scripts, and chain multiple operations together.

Using a nested command, you can count the number of lines in a file without creating an intermediate file:

wc -l $(find /path/to/directory -name "filename.txt")

You can find a specific process and terminate it using a nested command:

kill $(ps aux | grep "process_name" | grep -v "grep" | awk '{print $2}')

You can create a for loop that iterates through a list of files and compresses them using gzip:

#!/bin/bash
for file in $(find /path/to/directory -type f -name "*.txt"); do
gzip "$file"
done

In these examples, the command inside the $(...) is executed first, and its output is used as an argument for the outer command.

Note

The $() syntax is different from the ${} syntax, which is used for parameter expansion. Parameter expansion allows you to manipulate and retrieve the value of a variable. For example, you can extract a substring from a variable or modify the case of a variable.

My YouTube Channel

More shell script videos and linux tutorials on my YouTube Channel.

--

--