Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - Diference between echo `basename $HOME` and echo $(basename $HOME)

Tags:

bash

Thank you very much in advance for helping.

The title says everything: what's the difference between using:

echo `basename $HOME` 

and

echo $(basename $HOME)

Please notice that I know what the basename command does, that both syntax are valid and both commands give the same output.

I was just wondering if there is any difference between both and if it's possible, why there are two syntaxes for this.

Cheers

Rafael

like image 966
RafaelGP Avatar asked Jan 18 '13 13:01

RafaelGP


2 Answers

The second form has different escaping rules making it much easier to nest. e.g.

echo $(echo $(basename $HOME))

I'll leave working out how to do that with ` as an exercise for the reader, it should prove enlightening.

like image 126
Steve Avatar answered Nov 15 '22 07:11

Steve


They are one of the same.
please read this.

EDIT (from the link):
Command substitution

Command substitution allows the output of a command to replace the command itself. Command substitution occurs when a command is enclosed like this:

$(command)

or like this using backticks:

`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.

$ franky ~> echo `date`
Thu Feb 6 10:06:20 CET 2003

When the old-style backquoted form of substitution is used, backslash retains its literal meaning except when followed by "$", "`", or "\". The first backticks 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.

Command substitutions may be nested. To nest when using the backquoted form, escape the inner backticks with backslashes.

If the substitution appears within double quotes, word splitting and file name expansion are not performed on the results.

like image 39
Ofir Farchy Avatar answered Nov 15 '22 08:11

Ofir Farchy