BudiBadu Logo
Samplebadu

Shell Script by Example: Command Substitution

Bash 5.x

Capturing command output with this sample code showing the modern dollar-parentheses syntax, deprecated backtick notation for backward compatibility, nested command substitution, and using captured output in loops and variable assignments.

Code

#!/bin/bash

# Modern syntax $(...)
current_date=$(date +%Y-%m-%d)
echo "Today is: $current_date"

# Old backtick syntax `...` (deprecated but common)
kernel_version=`uname -r`
echo "Kernel: $kernel_version"

# Nesting commands
files_count=$(ls $(pwd) | wc -l)
echo "Files in current dir: $files_count"

# Using output in loops
for file in $(ls *.txt); do
    echo "Found text file: $file"
done

Explanation

Command substitution allows you to execute a command and use its standard output as an argument to another command or assign it to a variable. The modern and preferred syntax is $(command), which is nestable and easier to read than the older backtick syntax. When the shell encounters command substitution, it runs the command in a subshell and replaces the substitution with the command's standard output, with trailing newlines removed.

The older backtick syntax `command` is still supported for backward compatibility but is discouraged in modern scripts. Backticks are harder to read because they resemble single quotes, and nesting them requires complex escaping of inner backticks. The $() syntax handles nesting naturally, allowing you to write $(command1 $(command2)) without escaping.

When using command substitution, be aware that the command executes in a subshell, meaning variable assignments within the substituted command don't affect the parent shell. If the command output contains spaces or newlines, you should typically wrap the substitution in double quotes like "$(command)" to preserve whitespace. Without quotes, the shell performs word splitting on the output, which can lead to unexpected behavior when processing filenames or multi-word strings.

Code Breakdown

4
$(date +%Y-%m-%d) executes date command and captures its formatted output.
8
Backticks `...` are deprecated but still found in legacy scripts.
12
$(ls $(pwd) | wc -l) demonstrates nesting; inner $(pwd) runs first.
16-18
Command substitution in for loop expands to list of matching files.