45

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?

4 Answers 4

63

There's no difference except in "nestability":

The $() is nestable:

$ echo $(echo "hi" $(echo "there"))

while the `` is not.

Sign up to request clarification or add additional context in comments.

1 Comment

Technically it can be nested, but it has to be escaped once more for each level, and as such is unmaintainable and ugly.
8

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.

Comments

5

$(...) and backticks are very similar. The only difference between the two is some details of what special characters are substituted in them; the Bash 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.

Comments

2

From https://tldp.org/LDP/abs/html/commandsub.html:

The $(...) form of command substitution treats a double backslash in a different way than `...`.

and

The $(...) form of command substitution permits nesting.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.