-1

I want to know why an extra echo will print in my shell. I'm using bash version 4.2.46(1).

echo `echo `echo $SHELL``

A interesting issue is if I replace '``' with $() it doesn't print extra echo:

echo $(echo `echo $SHELL`)

And I found that it prints extra echos in odd echo command numbers:

echo `echo `echo `echo `echo $SHELL````
  • 1
    That's what $() is for. Backticks don't nest. – PSkocik Dec 5 '15 at 19:59
  • And what backticks do? – Sepahrad Salour Dec 5 '15 at 20:05
8

Your two versions:

echo `echo `echo $SHELL``

and

echo $(echo `echo $SHELL`)

are not equivalent. The first backtick command substitution ends as soon as another backtick is seen:

When the old-style backquote form of substitution is used, [...] The first backquote not preceded by a backslash terminates the command substitution.

Your first version is actually equivalent to:

echo $(echo )echo $SHELL$()

which is why you get an "echo" in the output - the command you end up running (after substitutions and with extra whitespace removed) is just:

echo echo /bin/bash

so the output is "echo /bin/bash", just like if you wrote that command out directly.


If you must nest backticks, you can backslash the inner pairs to escape them. Your first command could be written correctly as:

echo `echo \`echo $SHELL\``

although I wouldn't recommend it — $( ... ) is made for nesting.

  • Thanks for your answer, therefore I have to escape inner backticks with `\`. – Sepahrad Salour Dec 5 '15 at 20:14
2

The equivalent to

echo $(echo `echo $SHELL`)

Or, even better:

echo $(echo $(echo $SHELL))

In backticks will be:

$ echo `echo \`echo $SHELL\``
/bin/sh

And that is exactly the main problem of backticks:

 Where exactly does a backtick start or end?

That is why the shell does not understand the line correctly. The shell understand the line to be:

echo echo `echo $SHELL`

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.