I\'m constantly confused by the rules for quoting and evaluating when I\'m writing bash scripts. I know some of the basics, like the difference between \'\' and \"\" and ``,
Use singlequotes ''
for quoting raw text (even backslashes do not escape anything in singlequotes):
> echo '\'
\
> echo '$PATH'
$PATH
Use doublequotes ""
for quoting text which contains things the shell shall evaluate like variables ($bla
), subshell calls ($(ls)
), and evaluations ($((5 + 3))
).
> echo "$PATH"
/home/alfe/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
> echo "$(ls | tail -1)"
bla
> echo "$((5 + 3))"
8
Use backticks ``
if for some reason you cannot use $()
(e. g. in the rare cases where you have to you sh
instead of bash
. Normally use $()
to gather the output of a subshell into the current command.
> echo "$(ls | tail -1) is the last file in the current dir."
bla is the last file in the current dir.
One of the main problems I run into with bash code of other people is missing doublequotes around something which often is just a word but in rare cases may be more than one word, or which can contain special characters. So use doublequotes wherever they are possible.
> a="four spaces"
> echo $a
four spaces
> echo "$a"
four spaces