0

Can I always expect the same results from these two forms?

For example:

for i in `seq 1 10`
for i in $(seq 1 10)

I've got the same result from the above two statements.

Jimin Byun
  • 3
  • 1
  • 4

1 Answers1

1

The difference between the two is in the treatment of special characters.

From the man page:

Command Substitution

Command substitution allows the output of a command to replace the command name. There are two forms:

      $(command)    

or

      `command`

Bash performs the expansion by executing command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting. The command substitution $(cat file) can be replaced by the equivalent but faster $(< file).

When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, `, or . The first backquote not preceded by a backslash terminates the command substitution. When using the $(command) form, all characters between the parentheses make up the command; none are treated specially.

With the $() form, you don't need to worry about escaping any special characters. This can be helpful if you have a complicated command that you just want to drop in place.

The backquoted form is useful when you want to do any kind of substitution within the command.

Here's an example of when the two differ:

XXX=x1.sh

YYY=`ls -l \$XXX`
ZZZ=$(ls -l \$XXX)

echo YYY = $YYY
echo ZZZ = $ZZZ

Output:

ls: cannot access $XXX: No such file or directory
YYY = -rwxr-xr-x. 1 dbush dbush 94 Apr 14 23:04 x1.sh
ZZZ =
chepner
  • 497,756
  • 71
  • 530
  • 681
dbush
  • 205,898
  • 23
  • 218
  • 273
  • 2
    I'm curious about *"The backquoted form is useful when you want to do any kind of substitution within the command."* -- you can nest `$(...)`, so what special benefit does nesting backticks in `$(...)` provide? I guess you are referring to, e.g. `$(sed 's/\`stuff/\`other/')`? – David C. Rankin Apr 15 '18 at 02:54
  • The general consensus otherwise seems to be *"the backquoted form should simply be avoided; use the new syntax."* – tripleee Apr 15 '18 at 05:09