Bash – The old ticks vs parentheses issue: confused

bashcommand-substitutionshell

Since being corrected many years ago, I switched from backticks to $() for command expansion.

But I still prefer the backticks. It is fewer keystrokes and does not involve the Shift key.

I understand that the parentheses are preferable because it is less prone to the errors that backticks is prone to, but what is the reason for the rule to never use backticks?

Best Answer

The Bash FAQ gives a number of reasons to prefer parentheses to backticks, but there isn’t a universal rule that you shouldn’t ever use backticks.

The main reason to prefer parentheses in my view is that parsing inside $() is consistent with parsing performed outside, which isn’t the case with backticks. This means that you can take a shell command and wrap it with "$()" without much thought; that’s not true if you use backticks instead. This cascades, so wrapping a command which itself contains a substitution is easily done with "$()", not so with backticks.

Ultimately I think it’s a question of habit. If you choose to use backticks for simple cases, parentheses for others, you’ll have to make that choice every time you want to substitute a command. If you choose to always use parentheses, you never have to think about it again.

The latter can explain the presence of a “don’t use backticks” rule in certain coding guides: it simplifies development, and removes a source of errors for developers and reviewers. It also explains why using parentheses can be recommended even for one-liners: it’s hard to ingrain a habit for script-writing when it’s not applied everywhere.

(As far as keying goes, that depends on the keyboard layout; on my AZERTY keyboard, $() doesn’t involve any shifting, whereas backticks are quite painful to write.)

Related Question