There are two syntaxes for command substitution: with dollar-parentheses and with backticks.
top -p $(pidof init) and
top -p `pidof init` gives the same output. Are these two ways of doing the same thing, or are there differences?
The old-style backquotes
` ` do treat backslashes and nesting a bit different. The new-style
$() interprets everything in between
( ) as a command.
echo $(uname | $(echo cat)) Linux echo `uname | `echo cat`` bash: command substitution: line 2: syntax error: unexpected end of file echo cat
works if the nested backquotes are escaped:
echo `uname | \`echo cat\`` Linux
echo $(echo '\\') \\ echo `echo '\\'` \
Apart from the technical point of view, the old-style
` ` has also a visual disadvantage:
- Hard to notice:
I like $(program) better than `program`
- Easily confused with a single quote:
- Not so easy to type (maybe not even on the standard layout of the keyboard)
(and SE uses
` ` for own purpose, it was a pain writing this answer :)
Obvious difference I observe is that you cannot nest backticks while you can nest
$(). Maybe both exist for legacy reasons. Similarly, the
source commands are synonyms.
$() does not work with old Bourne shell. But it has been years since I worked with old Bourne shell.
$() will use more system resource than using backticks, but is slightly faster.
In Mastering Unix shell scripting, Randal K. Michael had done a test in a chapter named "24 Ways to Process a File Line-by-Line".
To add to what others said here, you can use the backticks to simulate inline comments:
echo foo `# I'm a comment!` bar
The output is:
See the following for more information: https://stackoverflow.com/a/12797512 (Note also the comments below that post.)
$() syntax will not work with the old bourne shell.
With newer shells
` ` and
$() are equivalent but
$() is much more convenient to use when you need to nest multiple commands.
For instance :
echo $(basename $(dirname $(dirname /var/adm/sw/save )))
is easier to type and debug than :
echo `basename \`dirname \\\`dirname /var/adm/sw/save \\\`\``