问题
I have to run commands, in a bash script, and within this bash script I have to run other commands. I am running CentOS.
I found 2 ways to do this on blogs and manuals:
1) using the ticks or accent char
command `sub command`
or
2) using the dollar sign and parentheses
command $(sub command)
What is the difference between the 2 and which one is preferable to use?
回答1:
There's no difference except in "nestability":
The $() is nestable:
$ echo $(echo "hi" $(echo "there"))
while the `` is not.
回答2:
Others have pointed out the difference in syntax (basically, $() is slightly cleaner wrt nesting and escapes), but nobody's mentioned what I consider the more important difference: $() is much easier to read. It doesn't look like single-quotes (which mean something totally different), and the opening and closing delimiters are different, making it easier to visually distinguish its contents.
For your own scripts, this may not be really critical; code readability is good, but functionality is more important. But for anyone writing tutorials, sample code, stackoverflow answers, etc, readability is much more important. People will type single-quotes instead of backquotes when typing in examples, etc, and then get confused when it doesn't work as expected.
So for everyone writing examples on stackoverflow: please save your readers some trouble, and always use the $() form.
回答3:
$(...) and backticks are very similar. The only difference between the two is some details of what special characters are substituted in them; the manual explains better than I could:
When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, `, or . The first backquote 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.
This makes it a bit easier to nest $(...), for instance. Besides that, though, there's no difference.
回答4:
Quoting from http://tldp.org/LDP/abs/html/commandsub.html:
- The $(...) form of command substitution treats a double backslash in a different way than `...`.
- The $(...) form of command substitution permits nesting
Hope this helps!
回答5:
I must agree with Gordon in the fact that $() is way cleaner. I struggled for 2 hours editing my .bash_profile to add homebrew bash completion only to find that I should've been using ` and not '.
来源:https://stackoverflow.com/questions/8663595/bash-for-inline-command