Differences between revisions 2 and 4 (spanning 2 versions)
Revision 2 as of 2007-05-09 18:20:43
Size: 792
Editor: GreyCat
Comment:
Revision 4 as of 2007-09-14 11:52:14
Size: 1499
Editor: leon
Comment: are they really surprising? maybe we can generalize to all quotes instead?
Deletions are marked like this. Additions are marked like this.
Line 16: Line 16:
 * Backslashes (\) inside backticks are handled in a non-obvious manner. ''(Example desired!)'' Inside {{{$()}}}, there are no such surprises.  * 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.

Backslashes are no more no less surprising than elsewhere IMHO
{{{
  echo `echo \a` # prints a
  echo `echo \\a` # prints a
  echo `echo \\\a` # prints \a
  echo `echo \\\\a` # prints \a
  echo $(echo \a) #prints a
  echo $(echo \\a) prints \a
  echo $(echo \\\a) prints \a
  echo $(echo \\\\a) prints \\a
}}}
the same sort of things happens without any quotes or within "".

I suspect the real advantage of $( ) here is that you don't need to take extra care of the quotes (\ ""), you just put them as usual, ie
echo "`echo \"foo bar\"`" vs echo "$( echo "foo bar")" -- pgas

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.

Backslashes are no more no less surprising than elsewhere IMHO

  echo `echo \a` # prints a
  echo `echo \\a` # prints a
  echo `echo \\\a` # prints \a
  echo `echo \\\\a` # prints \a
  echo $(echo \a)  #prints a
  echo $(echo \\a) prints \a
  echo $(echo \\\a) prints \a
  echo $(echo \\\\a) prints \\a

the same sort of things happens without any quotes or within "".

I suspect the real advantage of $( ) here is that you don't need to take extra care of the quotes (\ ""), you just put them as usual, ie echo "echo \"foo    bar\"" vs echo "$( echo "foo bar")" -- pgas

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

BashFAQ/082 (last edited 2022-02-19 00:13:59 by larryv)