I am having difficulties figuring out some the nuances between single and double quotes within a variable context
I define:
foo=pwd
then run these:
echo $'$foo'
Which echos $foo
(meaning the first $
in my echo command is dropped)
echo $"$foo"
This echos pwd
(which means the bash expands $foo
, my variable, to its value)
echo $`$foo`
Finally this echos $~/scripts
(I expected it to print ~/scripts
and not $~/scripts
)
can somebody help me figure out these differences?
Best Answer
echo $'$foo'
: the$'[...]'
token around$foo
interprets$foo
literally (as$foo
) and tries to expand ANSI C-like escape sequences in it, which are not present, soecho
yields$foo
;echo $"$foo"
: the$"[...]"
token around$foo
expands$foo
to its value (pwd
) and tries to translate it if the current locale is not POSIX / C; this is not happening, because either the current locale is POSIX / C or a translation forpwd
is not available, soecho
yieldspwd
;echo $`$foo`
: the`[...]`
token around$foo
allows the expansion of$foo
, so$foo
is expanded to its value (pwd
); the expanded value is run in a subshell, whose output (~/scripts
) replaces the whole`[...]`
token, soecho
yields the$
token followed by the~/scripts
token ($~/scripts
).Ultimately, the last one prints
$~/scripts
because$`foo`
is a combination of a literal$
followed by a command substitution; so the leading$
is interpreted as a literal$
and the trailing`$foo`
as a command substitution.