Why use $() instead of ` (the backtick) for command substitution?
In my book Linux Phrasebook I told readers that if they want to use the output of a command inside another command (known as command substitution), they should use $() instead of ` (the backtick). In other words, instead of this:
mkdir folder_`date +%Y%m%d`Do this:
mkdir folder_$(date +%Y%m%d)Here’s a slightly more complicated (yet overly simplified, as you’ll see) example. Instead of this:
for i in `cat /path/to/some/file`
do
something $i
doneYou should instead do this:
for i in $(cat /path/to/some/file)
do
something $i
doneA few days ago, a reader wrote to me & asked the following:
I’m seeking clarification on a position you took in your book, advising readers to use $() over backticks. Could you please explain why?
Here’s what I wrote back:
Here are some reasons:
$()is easier to read, especially with smaller fonts that can make the backtick really hard to see. To me, this is a big one.- The backtick is very similar to a apostrophe; heck, a lot of the time I’ve seen backticks used as apostrophes!
- The
$()makes nesting command substitutions easier. In other words, you can do this:cd $(mkdir folder_$(date +%Y%m%d)).- It’s more like the programming notations that others are familiar with. I don’t know of anything that uses the backtick.
- It’s recommended that you do it that way!
More info: