My command is this:
df=$(echo `df -h | head -3`)
echo $df
I would expect it to display the first three lines of df -h
output as such:
Filesystem Size Used Avail Use% Mounted on
/abc/asdf 16G 5.6G 9.4G 38% /
abcd 1.9G 12K 1.9G 1% /dev
Instead, it outputs this:
Filesystem Size Used Avail Use% Mounted on /abc/asdf 16G 5.6G 9.4G 38% / abcd 1.9G 12K 1.9G 1% /dev
echo $df
outputs the newline character in my shell script?head
?Quote the variable to prevent word splitting:
echo "$df"
99% of the time you should quote variables when you use them. Only use variables unquoted if you really want them to be subject to word splitting and globbing. There are some occasions where quotes are not needed (e.g. assignments like a=$b
), but the redundant quotes won't hurt.
I just notieced that you're also using echo
inside the $()
. I'm not sure why, but you also need quotes there:
df=$(echo "`df -h | head -3`")
But you don't need echo, you can just write:
df=$(df -h | head -3)