Skip to content
Advertisement

Unexpected behaviour of double quotes in bash script

I’ve created a variable which looks like this:

firstAndLastLines="$(cat /etc/passwd | head -$n | cut -f5 -d':') $(cat /etc/passwd | tail -$n | cut -f5 -d':') "

If I print it to the terminal, using echo $firstAndLastLines, I get the following output:
root bin daemon adm lp Privilege-separated SSH Account used by the trousers package to sandbox the tcsd daemon Norbert Fogarasi

But, if I use echo "$firstAndLastLines", I get the following, separated by new lines:

root
bin
daemon
adm
lp 
Privilege-separated SSH
Account used by the trousers package to sandbox the tcsd daemon

Norbert Fogarasi`

I wondered, why is this happening? It does not have to be the same? `

Advertisement

Answer

Explanation in bash man:

Enclosing characters in double quotes preserves the literal value of all characters within the quotes, with the exception of $, `, ,

Advertisement