Home » Have backticks (i.e. `cmd`) in *sh shells been deprecated?

Have backticks (i.e. `cmd`) in *sh shells been deprecated?

Solutons:


There are two different meanings of “deprecated.”

be deprecated: (chiefly of a software feature) be usable but regarded as obsolete and best avoided, typically due to having been superseded.

—New Oxford American Dictionary

By this definition backticks are deprecated.

Deprecated status may also indicate the feature will be removed in the future.

—Wikipedia

By this definition backticks are not deprecated.

Still supported:

Citing the Open Group Specification on Shell Command Languages,
specifically section 2.6.3 Command Substitution, it can be seen that both forms of command substitution, backticks (`..cmd..`) or dollar parens ($(..cmd..)) are still supported insofar as the specification goes.

Command substitution allows the output of a command to be substituted in place
of the command name itself. Command substitution shall occur when the command
is enclosed as follows:

$(command)
          

or (backquoted version):

`command`

The shell shall expand the command substitution by executing command in a
subshell environment (see Shell Execution Environment) and replacing the
command substitution (the text of command plus the enclosing $() or
backquotes) with the standard output of the command, removing sequences of one
or more <newline> characters at the end of the substitution. Embedded <newline> characters before the end of the output shall not be removed; however,
they may be treated as field delimiters and eliminated during field splitting,
depending on the value of IFS and quoting that is in effect. If the output
contains any null bytes, the behavior is unspecified.

Within the backquoted style of command substitution, <backslash> shall retain
its literal meaning, except when followed by: ‘$’, ‘`‘, or <backslash>. The
search for the matching backquote shall be satisfied by the first unquoted
non-escaped backquote; during this search, if a non-escaped backquote is
encountered within a shell comment, a here-document, an embedded command
substitution of the $(command) form, or a quoted string, undefined results
occur. A single-quoted or double-quoted string that begins, but does not end,
within the “`...`” sequence produces undefined results.

With the $(command) form, all characters following the open parenthesis to
the matching closing parenthesis constitute the command. Any valid shell
script can be used for command, except a script consisting solely of
re-directions which produces unspecified results.

So then why does everyone say that backticks have been deprecated?

Because most of the use cases should be making use of the dollar parens form instead of backticks. (Deprecated in the first sense above.) Many of the most reputable sites (including U&L) often state this as well, throughout, so it’s sound advice. This advice should not be confused with some non-existent plan to remove support for backticks from shells.

  • BashFAQ #082 – Why is $(…) preferred over `…` (backticks)?

    `...` is the legacy syntax required by only the very oldest of
    non-POSIX-compatible bourne-shells. There are several reasons to always
    prefer the $(...) syntax:

  • Bash Hackers Wiki – Obsolete and deprecated syntax

    This is the older Bourne-compatible form of the command substitution.
    Both the `COMMANDS` and $(COMMANDS) syntaxes are specified by POSIX,
    but the latter is greatly preferred, though the former is unfortunately
    still very prevalent in scripts. New-style command substitutions are widely
    implemented by every modern shell (and then some). The only reason for using
    backticks is for compatibility with a real Bourne shell (like Heirloom).
    Backtick command substitutions require special escaping when nested, and
    examples found in the wild are improperly quoted more often than not. See:
    Why is $(…) preferred over `…` (backticks)?.

  • POSIX standard rationale

    Because of these inconsistent behaviors, the backquoted variety of command substitution is not recommended for new applications that nest command substitutions or attempt to embed complex scripts.

NOTE: This third excerpt (above) goes on to show several situations where backticks simply won’t work, but the newer dollar parens method does, beginning with the following paragraph:

Additionally, the backquoted syntax has historical restrictions on the contents of the embedded command. While the newer “$()” form can process any kind of valid embedded script, the backquoted form cannot handle some valid scripts that include backquotes.

If you continue reading that section the failures are highlighted showing how they would fail using backticks, but do work using the newer dollar parens notation.

Conclusions

So it’s preferable that you use dollar parens instead of backticks but you aren’t actually using something that’s been technically “deprecated” as in “this will stop working entirely at some planned point.”

After reading all this you should have the take away that you’re strongly encouraged to use dollar parens unless you specifically require compatibility with a real original non-POSIX Bourne shell.

It’s not deprecated, but the backticks (`...`) is the legacy syntax required by only the very oldest of non-POSIX-compatible bourne-shells and $(...) is POSIX and more preferred for several reasons:

  • Backslashes () inside backticks are handled in a non-obvious manner:

    $ echo "`echo \a`" "$(echo \a)"
    a a
    $ echo "`echo \\a`" "$(echo \\a)"
    a \a
    # Note that this is true for *single quotes* too!
    $ foo=`echo '\'`; bar=$(echo '\'); echo "foo is $foo, bar is $bar" 
    foo is , bar is \
    
  • Nested quoting inside $() is far more convenient:

    echo "x is $(sed ... <<<"$y")"
    

    instead of:

    echo "x is `sed ... <<<"$y"`"
    

    or writing something like:

    IPs_inna_string=`awk "/`cat /etc/myname`/"'{print $1}' /etc/hosts`
    

    because $() uses an entirely new context for quoting

    which is not portable as Bourne and Korn shells would require these backslashes, while Bash and dash don’t.

  • Syntax for nesting command substitutions is easier:

    x=$(grep "$(dirname "$path")" file)
    

    than:

    x=`grep "`dirname "$path"`" file`
    

    because $() enforces an entirely new context for quoting, so each command substitution is protected and can be treated on its own without special concern over quoting and escaping. When using backticks, it gets uglier and uglier after two and above levels.

    Few more examples:

    echo `echo `ls``      # INCORRECT
    echo `echo `ls``    # CORRECT
    echo $(echo $(ls))    # CORRECT
    
  • It solves a problem of inconsistent behavior when using backquotes:

    • echo '$x' outputs $x
    • echo `echo '$x'` outputs $x
    • echo $(echo '$x') outputs $x
  • Backticks syntax has historical restrictions on the contents of the embedded command and cannot handle some valid scripts that include backquotes, while the newer $() form can process any kind of valid embedded script.

    For example, these otherwise valid embedded scripts do not work in the left column, but do work on the rightIEEE:

    echo `                         echo $(
    cat <<eof                     cat <<eof
    a here-doc with `              a here-doc with )
    eof                            eof
    `                              )
    
    
    echo `                         echo $(
    echo abc # a comment with `    echo abc # a comment with )
    `                              )
    
    
    echo `                         echo $(
    echo '`'                       echo ')'
    `                              )
    

Therefore the syntax for $-prefixed command substitution should be the preferred method, because it is visually clear with clean syntax (improves human and machine readability), it is nestable and intuitive, its inner parsing is separate, and it is also more consistent (with all other expansions that are parsed from within double-quotes) where backticks are the only exception and ` character is easily camouflaged when adjacent to " making it even more difficult to read, especially with small or unusual fonts.

Source: Why is $(...) preferred over `...` (backticks)? at BashFAQ

See also:

  • POSIX standard section “2.6.3 Command Substitution”
  • POSIX rationale for including the $() syntax
  • Command Substitution
  • bash-hackers: command substitution

Related Solutions

Joining bash arguments into single string with spaces

[*] I believe that this does what you want. It will put all the arguments in one string, separated by spaces, with single quotes around all: str="'$*'" $* produces all the scripts arguments separated by the first character of $IFS which, by default, is a space....

AddTransient, AddScoped and AddSingleton Services Differences

TL;DR Transient objects are always different; a new instance is provided to every controller and every service. Scoped objects are the same within a request, but different across different requests. Singleton objects are the same for every object and every...

How to download package not install it with apt-get command?

Use --download-only: sudo apt-get install --download-only pppoe This will download pppoe and any dependencies you need, and place them in /var/cache/apt/archives. That way a subsequent apt-get install pppoe will be able to complete without any extra downloads....

What defines the maximum size for a command single argument?

Answers Definitely not a bug. The parameter which defines the maximum size for one argument is MAX_ARG_STRLEN. There is no documentation for this parameter other than the comments in binfmts.h: /* * These are the maximum length and maximum number of strings...

Bulk rename, change prefix

I'd say the simplest it to just use the rename command which is common on many Linux distributions. There are two common versions of this command so check its man page to find which one you have: ## rename from Perl (common in Debian systems -- Ubuntu, Mint,...

Output from ls has newlines but displays on a single line. Why?

When you pipe the output, ls acts differently. This fact is hidden away in the info documentation: If standard output is a terminal, the output is in columns (sorted vertically) and control characters are output as question marks; otherwise, the output is...

mv: Move file only if destination does not exist

mv -vn file1 file2. This command will do what you want. You can skip -v if you want. -v makes it verbose - mv will tell you that it moved file if it moves it(useful, since there is possibility that file will not be moved) -n moves only if file2 does not exist....

Is it possible to store and query JSON in SQLite?

SQLite 3.9 introduced a new extension (JSON1) that allows you to easily work with JSON data . Also, it introduced support for indexes on expressions, which (in my understanding) should allow you to define indexes on your JSON data as well. PostgreSQL has some...

Combining tail && journalctl

You could use: journalctl -u service-name -f -f, --follow Show only the most recent journal entries, and continuously print new entries as they are appended to the journal. Here I've added "service-name" to distinguish this answer from others; you substitute...

how can shellshock be exploited over SSH?

One example where this can be exploited is on servers with an authorized_keys forced command. When adding an entry to ~/.ssh/authorized_keys, you can prefix the line with command="foo" to force foo to be run any time that ssh public key is used. With this...

Why doesn’t the tilde (~) expand inside double quotes?

The reason, because inside double quotes, tilde ~ has no special meaning, it's treated as literal. POSIX defines Double-Quotes as: Enclosing characters in double-quotes ( "" ) shall preserve the literal value of all characters within the double-quotes, with the...

What is GNU Info for?

GNU Info was designed to offer documentation that was comprehensive, hyperlinked, and possible to output to multiple formats. Man pages were available, and they were great at providing printed output. However, they were designed such that each man page had a...

Set systemd service to execute after fstab mount

a CIFS network location is mounted via /etc/fstab to /mnt/ on boot-up. No, it is not. Get this right, and the rest falls into place naturally. The mount is handled by a (generated) systemd mount unit that will be named something like mnt-wibble.mount. You can...

Merge two video clips into one, placing them next to each other

To be honest, using the accepted answer resulted in a lot of dropped frames for me. However, using the hstack filter_complex produced perfectly fluid output: ffmpeg -i left.mp4 -i right.mp4 -filter_complex hstack output.mp4 ffmpeg -i input1.mp4 -i input2.mp4...

How portable are /dev/stdin, /dev/stdout and /dev/stderr?

It's been available on Linux back into its prehistory. It is not POSIX, although many actual shells (including AT&T ksh and bash) will simulate it if it's not present in the OS; note that this simulation only works at the shell level (i.e. redirection or...

How can I increase the number of inodes in an ext4 filesystem?

It seems that you have a lot more files than normal expectation. I don't know whether there is a solution to change the inode table size dynamically. I'm afraid that you need to back-up your data, and create new filesystem, and restore your data. To create new...

Why doesn’t cp have a progress bar like wget?

The tradition in unix tools is to display messages only if something goes wrong. I think this is both for design and practical reasons. The design is intended to make it obvious when something goes wrong: you get an error message, and it's not drowned in...