Differences between revisions 1 and 3 (spanning 2 versions)
Revision 1 as of 2007-05-09 18:10:44
Size: 788
Editor: GreyCat
Comment: new question
Revision 3 as of 2007-09-13 19:19:33
Size: 895
Editor: BetterWorld
Comment: Add example for non-obvious backslashing behaviour
Deletions are marked like this. Additions are marked like this.
Line 2: Line 2:
== Why is $(...) preferred over `` (backticks)? == == Why is $(...) preferred over `...` (backticks)? ==
Line 15: Line 15:
 * Newbies who see {{{$()}}} don't normally press the wrong keys. On the other hand, newbie who see {{{`cmd`}}} often mangle it into {{{'cmd'}}} because they don't know what a backtick is.
 * Backslashes (\) inside backticks are handled in a non-obvious manner. ''(Example desired!)'' Inside {{{$()}}}, there are no such surprises.
 * Newbies who see {{{$()}}} don't normally press the wrong keys. On the other hand, newbies who see {{{`cmd`}}} often mangle it into {{{'cmd'}}} because they don't know what a backtick is.
 * Backslashes (\) inside backticks are handled in a non-obvious manner:

  {{{
  echo "`echo \\a`" #
prints a
  echo "`echo \\\a`" # prints \a
  echo "`echo \\\\a`" # prints \a}}}

Inside {{{$()}}}, there are no such surprises.

Anchor(faq82)

Why is $(...) preferred over `...` (backticks)?

For several reasons:

  • It makes nesting command substitutions easier. Compare:
    •   x=$(grep $(dirname "$path") file)
        x=`grep \`dirname "$path"\` file`
    It just gets uglier and uglier after two levels.
  • It's easier to read.
  • Newbies who see $() don't normally press the wrong keys. On the other hand, newbies who see `cmd` often mangle it into 'cmd' because they don't know what a backtick is.

  • Backslashes (\) inside backticks are handled in a non-obvious manner:
    •   echo "`echo \\a`"      # prints a
        echo "`echo \\\a`"     # prints \a
        echo "`echo \\\\a`"    # prints \a

Inside $(), there are no such surprises.

The only time backticks are preferred is when writing code for the oldest Bourne shells, which do not know about $().

BashFAQ/082 (last edited 2021-08-10 13:22:46 by GreyCat)