That's a great question about best practices!
While both $() and backticks (`) perform command substitution, it's generally recommended to prefer $(command) over backticks.
Here's why you should avoid backticks in most modern shell scripting:
-
Nesting Issues:
When you want to nest command substitutions (i.e., use the output of one command as part of another command that's also being substituted), backticks can become very tricky and hard to read. You'd have to escape the inner backticks with a backslash:# Nested with backticks (gets messy quickly) outer_var=`echo \`inner_command\``With
$(command), nesting is straightforward and much more readable:# Nested with $() (much clearer) outer_var=$(echo $(inner_command)) -
Escaping Characters:
Inside backticks, you have to be careful with certain characters like backslashes (\), dollar signs ($), and other backticks (`). They might require escaping, which makes your code harder to write and debug.$(command)handles most of these more gracefully, reducing the need for complex escaping. -
Readability:
The$(command)syntax is often considered more readable and easier to distinguish from single quotes (') or double quotes ("), especially for beginners or when quickly glancing over code. The backtick can sometimes be confused with a single quote. -
No Processing Inside:
With$(...), the content inside the parentheses is parsed as a regular shell command, which means you can have any valid shell syntax, including process substitution, nested command substitution, and function calls, without special escaping rules for the outer command substitution.
In summary:
You can still use backticks, and they will work in most shells. However, for cleaner, more robust, and easier-to-read scripts, especially when dealing with nesting or complex commands, always opt for $(command). It's the modern, safer, and more flexible choice for command substitution.
Do you have any examples in mind where you've seen backticks used that you'd like to understand better? I'm happy to elaborate!