Command Substitution with $(...)

Su Suriya Ravichandran Updated 06 Dec 2026
9 min read ·Lesson 48 of 205

Command substitution lets one command use the output of another. Bash runs the command written inside $(...), captures what it prints, and replaces the whole $(...) expression with that text. It is how a script stores the current date in a variable, counts the files in a folder, or builds a command from the result of an earlier one.

Understanding the Concept

Normally a command prints its output to the terminal. With command substitution, Bash intercepts that output instead and puts it into the command line, as if you had typed it yourself.

today=$(echo 2026-11-21)
echo "Today: $today"

Output:

Today: 2026-11-21

Bash ran echo 2026-11-21, captured the text 2026-11-21 that it would have printed, and assigned that text to the variable today. The second line then used the variable. In real scripts the inner command is usually something like date, but echo keeps the example predictable.

Command substitution is an expansion, so Bash performs it while processing the line, before the outer command runs. The outer command never sees $(...). It only sees the text that replaced it.

Syntax

$(command)

The command may be a single program, a pipeline, or several commands separated by semicolons. Everything written between the parentheses runs in a subshell, which is a child copy of the current shell.

count=$(ls d | wc -l)
echo "d has $count entries"

With a folder d that contains three files, the output is:

d has 3 entries

The pipeline ls d | wc -l ran inside the substitution. ls listed the files, wc -l counted the lines, and the number 3 replaced the $(...) expression.

You can also place a substitution directly inside a double-quoted string:

printf 'hello file\nline2\n' > data.txt
echo "Lines in data.txt: $(wc -l < data.txt)"

Output:

Lines in data.txt: 2

wc -l < data.txt reads the file through input redirection, so wc prints only the number without the file name.

The Older Backtick Form

An older syntax wraps the command in backticks:

echo `echo old-style`
echo $(echo new-style)

Output:

old-style
new-style

Both forms do the same job, but $(...) is easier to read and much easier to nest. Inside backticks, an inner pair of backticks must be escaped with backslashes. Inside $(...), nesting needs no escaping:

echo "nested: $(echo "outer $(echo inner)")"
echo `echo \`echo inner\``

Output:

nested: outer inner
inner

In the first command, each pair of quotes inside a $(...) is independent of the quotes outside it, so you can nest without any extra escaping. The backtick version needs 0 for the inner pair. Prefer $(...) in all new scripts. You will still meet backticks in older scripts, so it helps to recognize them.

How the Captured Output Is Processed

Bash does not use the output as is. Two rules shape the result.

Trailing Newlines Are Removed

Every newline at the end of the output is stripped. Newlines inside the output remain.

x=$(printf 'a\n\n\n')
printf '[%s]\n' "$x"

Output:

[a]

printf produced a followed by three newlines. The substitution removed all three. This is why $(date) produces a clean value without a newline at the end, which is usually what you want.

Quoting Decides Whether the Result Is Split

When a substitution is not quoted, Bash splits the result into words at spaces, tabs and newlines, and then expands wildcards in those words. When it is inside double quotes, the result stays as one word.

lines=$(printf 'one\ntwo\nthree\n')
echo "$lines"
echo $lines

Output:

one
two
three
one two three

The quoted version preserved the line breaks. The unquoted version was split into three words, and echo joined them with single spaces.

The effect matters most when the output contains spaces:

files=$(printf 'my file.txt\nother.txt\n')
printf '[%s]\n' $files
printf '[%s]\n' "$files"

Output:

[my]
[file.txt]
[other.txt]
[my file.txt
other.txt]

The unquoted form broke my file.txt into two words, which would be wrong for a command that expects file names. The quoted form kept everything together as one argument. To handle file names that contain spaces correctly, use a loop that reads lines or an array, as shown later in this lesson. Quote "$(...)" whenever you want exactly one argument.

Using the Result in Different Places

A substitution can appear anywhere a word can appear: in a variable assignment, an argument, a string, a loop list or an arithmetic expression.

n=$(echo 5)
echo $((n * 2))

Output:

10

The substitution produced the text 5, which was stored in n and used in arithmetic. The next lesson covers arithmetic expansion in detail.

The basename and dirname commands are a typical pair of substitutions in a script:

p=/var/log/syslog
echo "$(basename "$p") in $(dirname "$p")"

Output:

syslog in /var/log

Notice that the inner quotes around "$p" are separate from the outer quotes around the whole string. Because $(...) starts a new quoting context, this nesting is correct and safe.

Reading a File with $(<file)

Bash has a shortcut for reading a whole file into a value. It does not start cat:

c=$(<data.txt)
echo "$c"

Output:

hello file
line2

$(<file) reads the file directly. As with any substitution, trailing newlines at the end are removed.

Providing a Default Value

A substitution can supply a fallback with parameter expansion. Bash runs the command only when the fallback is needed:

unset NAME
echo "${NAME:-$(echo fallback)}"

Output:

fallback

Because NAME was unset, Bash used the text after :-, and that text contained a substitution, which ran and produced fallback.

Exit Status of a Substitution

Capturing a command's output does not hide its exit status. For a plain assignment, the status of the assignment is the status of the command inside:

v=$(false); echo "status after false: $?"
v=$(exit 3); echo "status: $?"

Output:

status after false: 1
status: 3

$? holds the exit status of the last command, here the assignment. Since it takes the status from the command in the substitution, you can test it directly in an if:

if out=$(grep -c line data.txt); then echo "grep ok: $out"; fi
if out=$(grep -c nomatch data.txt); then echo "ok"; else echo "grep failed, out=[$out] status=$?"; fi

Output:

grep ok: 1
grep failed, out=[0] status=1

grep -c counts matching lines and exits with status 1 when the count is zero, so the second if took the else branch even though grep printed 0. The captured output and the exit status are two separate pieces of information.

The local Pitfall

Combining local with a substitution in a single line hides the status, because local itself succeeds:

f() { local r=$(false); echo "local status: $?"; }
f
g() { local r; r=$(false); echo "split status: $?"; }
g

Output:

local status: 0
split status: 1

In f, the last command to run was local, which exits with status 0. The failure of false was lost. In g, the declaration and the assignment are separate statements, so the failure is preserved. The same difference decides whether set -e stops a script: with the separate form it does, with the combined form it does not.

Which Output Is Captured

Only standard output is captured. Error messages go to the terminal unless you redirect them:

r=$(ls /nonexistent 2>&1)
echo "captured: $r"
r2=$(ls /nonexistent 2>/dev/null)
echo "captured2: [$r2]"

Output:

captured: ls: cannot access '/nonexistent': No such file or directory
captured2: []

2>&1 sends standard error to the same place as standard output, so the message was captured. 2>/dev/null discarded the error, leaving an empty value.

Substitutions Run in a Subshell

The commands inside $(...) run in a child shell, so changes they make to variables or the current directory do not affect the parent:

count=1
out=$(count=99; echo "inner $count")
echo "$out / outer $count"

cd /tmp
here=$(cd /usr && pwd)
echo "$here then $(pwd)"

Output:

inner 99 / outer 1
/usr then /tmp

The assignment count=99 and the cd /usr happened only inside the subshell. The parent shell kept count equal to 1 and stayed in /tmp. This isolation is useful: you can change directories or variables for a quick calculation without disturbing the rest of the script.

Looping Over Output and Building Arrays

A substitution can supply the list for a for loop. Bash splits the unquoted result at whitespace:

for w in $(printf 'a b c'); do echo "item $w"; done

Output:

item a
item b
item c

This works for simple words, but it breaks on values that contain spaces. For lines of text, mapfile reads each line into an array element without splitting on spaces:

mapfile -t arr < <(printf 'x y\nz\n')
printf '[%s]\n' "${arr[@]}"

Output:

[x y]
[z]

mapfile -t stores each line as one element and removes the newline. The < <(...) form is process substitution, which is covered in a later lesson. It is shown here only because it keeps each line intact.

Problems That Can Occur

A failing command inside a substitution. If the command cannot be found, the substitution returns status 127 and its error message appears on standard error:

r=$(nosuchcmd 2>&1); echo "status $? msg: $r"

Output:

status 127 msg: script.sh: line 12: nosuchcmd: command not found

The script name and line number in the message depend on the script you ran.

set -e and substitutions. When set -e is active, a plain assignment such as v=$(false) makes the script exit, because the assignment takes the failing status:

bash -c 'set -e; v=$(false); echo not-reached'
echo "bash -c status $?"

Output:

bash -c status 1

The text not-reached was never printed, and the child shell exited with status 1.

Null bytes. Bash variables cannot hold the null byte. If the output contains one, Bash drops it and prints a warning:

v=$(printf 'a\0b' 2>&1); printf '[%s]\n' "$v"

Output:

script.sh: line 14: warning: command substitution: ignored null byte in input
[ab]

For data that may contain null bytes, such as file names produced by find -print0, read from the command with a loop rather than capturing it.

Practical Examples

Count the entries in a directory, then use the number in a message:

count=$(ls d | wc -l)
echo "d has $count entries"

Store a Unix timestamp and use it in arithmetic:

start=$(date +%s)
echo "epoch is numeric: $(( start > 0 ))"

Output:

d has 3 entries
epoch is numeric: 1

The date +%s command prints the number of seconds since 1970. The comparison start > 0 is true, so arithmetic expansion printed 1. Real scripts commonly capture a start time and a finish time and subtract them to report how long a task took.

Find the first word alphabetically in a list:

words=$(printf 'apple\nfig\nbanana\n')
echo "$words" | sort | head -n 1

Output:

apple

Because $words is quoted, the line breaks are kept, sort orders the three lines, and head -n 1 keeps the first.

Put a command's output into the middle of a longer message:

echo "There are $(printf 'a\nb\nc\n' | wc -l) lines"

Output:

There are 3 lines

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Command Substitution with $(...) and get answers drawn from it.

Signed-in readers only.