Difference between reverse quotation marks (') and $ () in Shell
Echo`Echo\ $ Hostname'//Reverse quotation marksecho $(echo \$HOSTNAME) //$()
|
Someone asked today:
Echo 'echo \\\\\\ W' echo $ (echo \\\\\\\ w) Why is the output different?
This leads to another problem: is there a difference between quotation marks and $?
This is a very interesting question, but it is really difficult to explain it. Let's take a simple example and give a general explanation.
For example, we have a shell script named test. sh with two rows.
We can use sh-x test. sh to analyze how bash interprets the script. The returned information is as follows:
We can draw two conclusions:
In the back quotes, \ $ does not convert the special meaning of $ into the content contained in the back quotes. echo \ $ hostname is still interpreted as an echo $ HOSTNAME. The value of this variable is obtained and the output is reversed. the value returned by the quotation marks is the CentOS-1
$ () Is the opposite. $ is obviously escaped as a common character by \, so the variable value is not obtained, but the meaning of the string is returned, so $ HOSTNAME is returned.
This indicates that there is a special conversion between the backslash (\) and the backslash (\). At least we can see that when we use one \ directly, it will not escape itself. Now let's make some changes to the script content:
|
Echo`Echo\ $ Hostname'//Reverse quotation marksecho $(echo \\$hostname) //$() |
We added another backslash. This time we can see the output:
This time seems to have reversed:
The quotation marks indicate the literal meaning of $ HOSTNAME.
$ () As we wish to get the variable value, and properly output an escaped string \
Let's start an experiment and create a script named a. sh:
1 |
echo `echo \\\\ ` echo $(echo \\\\ ) |
Note: there is a space in front of the last backquotes and). Otherwise, the last backquotes and) will be commented out and will not be replaced by the ending symbol.
The result of using sh-x a. sh is as follows:
We can see that:
Four \ In backquotes are output as one \
4 \ in $ () is output as 2 \
We changed the script to eight \:
|
echo `echo \\\\\\\\ ` echo $(echo \\\\\\\\ ) |
Let's look at the output:
Therefore, we can conclude that:
The backticks themselves escape \ and retain their meanings. If we want to play the special meaning of \ In the backticks, we must use two backticks for representation.
Therefore, we can simply think of it in the back quotes:\\= \
$ () Does not need to be considered. It is the same as what we usually use:\= \
Off-the-Question: Anti-quotes are old and $ () is a new usage, whether in learning and testing or in actual work,$ () Is recommended.