I see two different forms in Bash scripts which seem to do the same:
`some command`
and
$(some command)
What is the difference between the two, and when should I use each one of them?
$() Command Substitution According to the official GNU Bash Reference manual: “Command substitution allows the output of a command to replace the command itself.
What you've typed is a backtick - it is the start of an instruction to bash to evaluate what you type as a command. The > is displayed to indicate you are still entering the command on the next line. If you close the backtick you'll find the whole command will run. E.g.
$? $0 is one of the most used bash parameters and used to get the exit status of the most recently executed command in the foreground. By using this you can check whether your bash script is completed successfully or not.
Command substitution in Bash allows us to execute a command and substitute it with its standard output. Note this command executes within a subshell, which means it has its own environment and so it will not affect the parent shell's environment.
There isn't any semantic difference. The backtick syntax is the older and less powerful version. See man bash, section "Command Substitution".
If your shell supports the $()
syntax, prefer it because it can be nested.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With