8

I have recently started to shift my shell scripting from utilizing backticks to parens to execute a command in situ and use the results in something else. Eg:

for line in `cat file`
do
    echo "$line"
done

Now I use parens, substituting thusly:

for line in $(cat file)
...

What is the actual difference between the two methods, and why is paren substitution considered better than backticks?

wonea
  • 1,817
  • 1
  • 23
  • 42
warren
  • 9,920
  • 23
  • 86
  • 147
  • (pedantry follows) Note that in bash, you can replace `$(cat file)` with `$(< file)` that is performed entirely in the shell (saving precious microseconds otherwise wasted spawning a cat process). – glenn jackman Feb 21 '12 at 18:45
  • 1
    (pedantry continued) [Never, ever, ever use `for` to parse something line-by-line.](http://mywiki.wooledge.org/BashPitfalls#for_i_in_.24.28ls_.2A.mp3.29) – u1686_grawity Feb 21 '12 at 18:51
  • @grawity - this is a contrivved example entirely to showcase the difference in the two approaches – warren Feb 21 '12 at 18:52
  • 3
    Also, [BashFAQ/082](http://mywiki.wooledge.org/BashFAQ/082) regarding this question. – u1686_grawity Feb 21 '12 at 18:54

1 Answers1

14

There is no functional difference, however $() makes nesting a bit nicer and easier to follow. Consider this silly example:

$ echo `echo \`echo \\\`echo foo\\\`\``
foo

vs

$ echo $(echo $(echo $(echo foo)))
foo

Now consider doing it with a complex series of commands that do something useful ;).

FatalError
  • 2,143
  • 1
  • 17
  • 15