Double quote and dollar prefix string in shell

218 Views Asked by At

In the question How to execute ssh-keygen without prompt I find they use the here string like this:

""$'\n'"y"

Why do they need double quote before $? It seems $'\n'y is equal to it:

bash$ cat - <<< ""$'\n'"y" | od -c
0000000 \n y \n
0000003
bash$ cat - <<< $'\n'y | od -c
0000000 \n y \n
0000003 
1

There are 1 best solutions below

1
tripleee On

There is no reason; the empty double-quoted string is completely unnecessary.

The shell uses quoting to group tokens which would otherwise be split. token is precisely equivalent to ""token or "token" (or """"""""""token or """t"o"k"e"n" etc if you will) after quote removal.

The only place you really need an empty string is when an argument should be a string of length zero (like printf '%s\n' "first line" "" "third line" where the penultimate argument is an empty string) though it can also occasionally be useful for disambiguation ("$HOMEdir" is distinct from "$HOME""dir" where the former attempts to expand a variable whose name is seven characters long; though usually you'd use "${HOME}dir" to make this distinction).


(Multiple adjacent quotes have no significance to the shell; """" is simply the empty string "" next to the empty string "".)