0
0
Bash Scriptingscripting~5 mins

Backticks and $() for command substitution in Bash Scripting

Choose your learning style9 modes available
Introduction
Backticks and $() let you run a command inside another command and use its result. This helps automate tasks by using outputs directly.
You want to save the output of a command into a variable.
You need to use the result of one command as input for another.
You want to run a command inside a script and use its output immediately.
You want to combine commands to create more complex automation.
You want to avoid typing output manually and reduce errors.
Syntax
Bash Scripting
variable=`command`
# or
variable=$(command)
Both backticks `` and $() run the command inside and replace it with the output.
$() is preferred because it is easier to read and can be nested.
Examples
Stores the current date and time in the variable current_date using backticks.
Bash Scripting
current_date=`date`
Stores the current date and time in the variable current_date using $(). This is clearer and preferred.
Bash Scripting
current_date=$(date)
Counts the number of files in the current folder and saves it in files_count.
Bash Scripting
files_count=$(ls | wc -l)
Shows how $() can be nested to run commands inside commands.
Bash Scripting
nested_example=$(echo $(date))
Sample Program
This script shows how to use backticks and $() to get the current user name and count files. It prints the results so you can see both methods work.
Bash Scripting
#!/bin/bash

# Get current user name using backticks
user_name=`whoami`

# Get current user name using $()
user_name_dollar=$(whoami)

# Print both results

echo "User name with backticks: $user_name"
echo "User name with \$(): $user_name_dollar"

# Count files in current directory
file_count=$(ls | wc -l)
echo "Number of files here: $file_count"
OutputSuccess
Important Notes
Using $() is better because it is easier to read and you can put one command inside another.
Backticks can be confusing if you need to nest commands, so prefer $().
Command substitution runs the command and replaces it with the output, so make sure the command outputs what you expect.
Time complexity depends on the command run inside substitution, not the substitution itself.
Common mistake: forgetting to quote variables holding command output can cause word splitting or errors.
Summary
Backticks `` and $() run commands and use their output inside scripts.
$() is easier to read and supports nesting commands.
Use command substitution to automate tasks by using command outputs directly.