Bird
Raised Fist0
Bash Scriptingscripting~10 mins

Backticks and $() for command substitution in Bash Scripting - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Backticks and $() for command substitution
Start script
↓
Run command inside backticks or $()
↓
Shell executes command
↓
Command outputs text
↓
Shell replaces substitution with output
↓
Use output in script
↓
Continue script execution
The shell runs the command inside backticks or $(), captures its output, and replaces the substitution with that output for use in the script.
Execution Sample
Bash Scripting
current_date=`date`
echo "Today is $current_date"
This script stores the output of the date command in a variable and then prints it.
Execution Table
StepActionCommand/SubstitutionOutput CapturedVariable StateEcho Output
1Execute command substitution`date`Fri Jun 14 12:00:00 UTC 2024current_date = 'Fri Jun 14 12:00:00 UTC 2024'
2Echo variableecho "Today is $current_date"current_date unchangedToday is Fri Jun 14 12:00:00 UTC 2024
3End scriptcurrent_date unchanged
💡 Script ends after printing the date stored in current_date.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
current_dateundefinedFri Jun 14 12:00:00 UTC 2024Fri Jun 14 12:00:00 UTC 2024Fri Jun 14 12:00:00 UTC 2024
Key Moments - 3 Insights
Why do we use backticks or $() around a command?
Because the shell runs the command inside them and replaces it with the command's output, as shown in execution_table step 1.
What happens if the command inside backticks produces multiple lines?
All output lines are captured as a single string with newlines preserved, and assigned to the variable, just like in step 1.
Is there a difference between using backticks and $()?
Both do command substitution, but $() is easier to read and nest, which helps avoid confusion in complex scripts.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of current_date after step 1?
A"date"
B"Fri Jun 14 12:00:00 UTC 2024"
C"Today is Fri Jun 14 12:00:00 UTC 2024"
Dundefined
💡 Hint
Check the 'Variable State' column in row for step 1 in execution_table.
At which step does the script print the final output?
AStep 2
BStep 3
CStep 1
DNo output is printed
💡 Hint
Look at the 'Echo Output' column in execution_table.
If we replace backticks with $(), how does the execution table change?
AEcho output changes to command name
BVariable current_date becomes empty
CNo change in output or variable state
DScript fails to run
💡 Hint
Both backticks and $() perform command substitution similarly, as explained in key_moments.
Concept Snapshot
Command substitution runs a command inside backticks (`command`) or $() and replaces it with the output.
Use it to capture command output into variables.
Example: current_date=`date` or current_date=$(date).
$() is preferred for readability and nesting.
The shell replaces the substitution before running the rest of the script.
Full Transcript
In bash scripting, backticks (`command`) and $() are used for command substitution. This means the shell runs the command inside them and replaces the whole expression with the command's output. For example, current_date=`date` runs the date command and stores its output in the variable current_date. Then echo "Today is $current_date" prints the stored date. Both backticks and $() work the same, but $() is easier to read and nest. The execution table shows step-by-step how the command runs, output is captured, and the variable is set. This helps beginners see how command substitution works in practice.

Practice

(1/5)
1. What does the command substitution syntax $(date) do in a bash script?
easy
A. Creates a new variable named date
B. Runs the date command and replaces $(date) with its output
C. Comments out the date command
D. Prints the literal string $(date) without running the command

Solution

  1. Step 1: Understand command substitution

    Command substitution runs the command inside $() and replaces it with the command's output.
  2. Step 2: Apply to $(date)

    The date command outputs the current date and time, so $(date) is replaced by that output.
  3. Final Answer:

    Runs the date command and replaces $(date) with its output -> Option B
  4. Quick Check:

    Command substitution = runs command and inserts output [OK]
Hint: Remember: $() runs command and inserts output [OK]
Common Mistakes:
  • Thinking it creates a variable
  • Confusing it with comments
  • Expecting literal string output
2. Which of the following is the preferred syntax for command substitution in bash?
easy
A. echo `ls -l`
B. echo $(ls -l
C. echo $[ls -l]
D. echo $(ls -l)

Solution

  1. Step 1: Identify valid command substitution syntax

    Command substitution uses either backticks `command` or $(command). Both the backtick version and the incomplete $() version look valid at first.
  2. Step 2: Check for best practice and syntax correctness

    echo `ls -l` uses backticks which are valid but less readable and harder to nest. echo $(ls -l) uses $() which is modern and preferred. echo $[ls -l] uses invalid syntax with $[]. echo $(ls -l misses closing parenthesis.
  3. Final Answer:

    echo $(ls -l) -> Option D
  4. Quick Check:

    Use $() for clear command substitution [OK]
Hint: Use $() for command substitution, it's clearer and nestable [OK]
Common Mistakes:
  • Using $[] which is arithmetic expansion, not command substitution
  • Missing closing parenthesis
  • Confusing backticks with other symbols
3. What will be the output of this script snippet?
files=$(ls /tmp)
echo "$files"
medium
A. Shows an error because of missing quotes
B. Prints the literal string '$(ls /tmp)'
C. Lists all files and directories inside /tmp one per line
D. Prints nothing because variable is empty

Solution

  1. Step 1: Understand command substitution with ls

    The command ls /tmp lists files in /tmp. Using files=$(ls /tmp) stores that output as a string with filenames separated by newlines.
  2. Step 2: Echo the variable with quotes

    Using echo "$files" prints the content of files preserving newlines, so it lists all files and directories one per line.
  3. Final Answer:

    Lists all files and directories inside /tmp one per line -> Option C
  4. Quick Check:

    Command substitution stores output string = list of files [OK]
Hint: Command substitution stores output as string, echo prints it [OK]
Common Mistakes:
  • Expecting literal command string output
  • Confusing quotes causing errors
  • Assuming variable is empty
4. Identify the error in this script snippet:
current_dir=`pwd
 echo "Current directory is: $current_dir"
medium
A. Missing closing backtick for command substitution
B. Incorrect use of double quotes
C. Variable name is invalid
D. No error, script runs fine

Solution

  1. Step 1: Check command substitution syntax

    The command substitution using backticks must start and end with backticks. Here, the closing backtick is missing after pwd.
  2. Step 2: Analyze impact of missing backtick

    Without the closing backtick, bash will throw a syntax error and not run the script properly.
  3. Final Answer:

    Missing closing backtick for command substitution -> Option A
  4. Quick Check:

    Backticks must be paired to run commands [OK]
Hint: Always close backticks to avoid syntax errors [OK]
Common Mistakes:
  • Forgetting to close backticks
  • Misplacing quotes inside command substitution
  • Assuming variable names cause errors
5. You want to store the number of files in your home directory in a variable file_count. Which command correctly uses command substitution to do this?
hard
A. file_count=$(ls ~ | wc -l)
B. file_count=`ls ~ wc -l`
C. file_count=$(ls ~ wc -l)
D. file_count=ls ~ | wc -l

Solution

  1. Step 1: Understand the command to count files

    To count files, we list them with ls ~ and pipe to wc -l to count lines (files).
  2. Step 2: Use correct command substitution syntax

    file_count=$(ls ~ | wc -l) correctly uses $(ls ~ | wc -l) to run the full command and store output in file_count. The other options miss the pipe or fail to use command substitution.
  3. Final Answer:

    file_count=$(ls ~ | wc -l) -> Option A
  4. Quick Check:

    Use $() with full command and pipe inside [OK]
Hint: Use $() with full command including pipes for substitution [OK]
Common Mistakes:
  • Missing pipe between commands
  • Using backticks without pipe
  • Assigning command without substitution
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard