When To Use $(…) Vs Backticks For Command Substitution

When to Prefer $(…) Over Backticks

The $(…) syntax for command substitution, also known as the dollar-paren syntax, has several advantages over using backticks “:

  • $(…) substitutions are more readable and less visually cluttered in most cases
  • Nested substitutions and quoting work better with $(…) compared to backticks
  • The $(…) style is supported in all major modern shells including Bash, Zsh, fish, whereas backtick support can be limited in some cases

Code snippets using $(…) tend to be easier to read at a glance compared to lines filled with hard-to-spot backticks. Backticks also visually blend in with single and double quotes in strings, while $(…) stands out more clearly. So for code maintainability and appearances, $(…) is generally preferred.

When command substitutions are nested (a substitution within a substitution), backticks can fall short while $(…) handles arbitrary levels of nesting gracefully. We’ll explore nested substitutions more later.

In today’s landscape, $(…) enjoys nearly universal shell compatibility while backtick support varies more across shells. The $(…) syntax is standardized in POSIX shells like Bash, plus common non-POSIX shells. Preferring $(…) over backticks ensures better portability across environments.

The Legacy of Backticks “

Backticks originated in Unix shells as the first option available for substituting the output of a command inline. They continue to be supported for backwards compatibility reasons in most shells today including:

  • Bash – Default shell on most Linux systems
  • Zsh – Common user shell on macOS and Linux
  • Fish – User-friendly shell for interactive use
  • tcsh – Enhanced C shell, standard on some Unix systems

While innovative at the time, backticks have drawbacks when it comes to readability, versatility, and standardization. But they remain functional for simple command substitution in many shells.

The exceptions are some minimal embedded shells and non-POSIX-compliant environments that may not recognize backticks. In contrast, $(…) works across the board.

Command Substitution Basics

Command substitution allows executing a shell command or program inline, and substituting its standard output text into a larger command or script. The syntax options for performing substitution are backticks “ or $(…) – both will run the contained command and place the results in-line where the syntax is written.

For example, to search a file called log.txt for the text “error” and print any matching lines in the script:

  echo "Errors: " $(grep "error" log.txt)

The command `grep “error” log.txt` is run and produces output text. The backticks “ or $(…) contain the command so it runs first, takes the output, and swaps the command itself with the output text in its place when executed.

This lets you run external programs from within scripts and larger commands, while interacting with their output just like any other text. Command substitution sees heavy use in shell scripting to dynamically generate text on the fly.

Proper Nesting with $(…)

Attempting to nest backticks inside other backticks can get messy. Escaping the inner backticks is required, but the escaping rules can differ by shell resulting in compatibility issues. $(…) simplifies this scenario with standard support for nesting.

For example, running a grep command substitution inside an awk substitution requires escaping with backticks:

  awk '{print `grep -c "example" "$0"`}' file

With $(…), arbitrary levels of nesting work cleanly:

  awk '{print $(grep -c "example" $0)}' file

The inner $(grep…) substitution runs first, passes its output to awk, then the outer awk script substution runs with the passed text. Multi-level nesting provides flexibility when needing output from multiple programs at once.

Escaping Quotes and Special Characters

With backticks, careful escaping is required whenever the substituted command itself needs quotes or special characters. $(…) handles this escaping automatically without interference.

For example, running an inline awk command with single quotes requires backslash escaping the contained backticks:

 
  new=$(echo 'awk '\''{print $1}'\'' file')

With $(…) the quotes and escaping are cleaner without backslashes:

  new=$(echo 'awk '{print $1}' file')  

The $(…) syntax keeps the inside of the command substitution isolated from outside strings or quotes. This avoids conflicts and ensures passed arguments are interpreted correctly.

When Backticks “ May Still Apply

For very basic command substitution without nested or special characters, backticks can still be handy.

Older Unix shells may only recognize backticks. So they remain useful for backwards compatibility with archaic scripts and environments.

If existing infrastructure expects backtick syntax, switching could necessitate non-trivial changes. Some admins and developers simply prefer typing backticks out of habit as well.

But for widely portable scripts targeting primarily modern POSIX-style shells, $(…) is best. Backticks are perfectly functional but have quirks to workaround compared to $().

Leave a Reply

Your email address will not be published. Required fields are marked *