George V. Reilly

Quoting in Bash

Various Bash guides recommend putting quotes around just about everything. I had a script that contained this line:

sudo apt-get install --yes $(cat "$BUILD/install_on_aws_ubuntu.txt")

While refac­tor­ing, I put another set of quotes around the $(cat ...) out of an abundance of caution:

sudo apt-get install --yes "$(cat "$BUILD/install_on_aws_ubuntu.txt")"

Several other changes later, I couldn’t figure out why my script had stopped working.

Here’s what happened:

$ cat $HOME/tmp/demo.txt
foo
bar
quux

$ echo $(cat "$HOME/tmp/demo.txt")
foo bar quux

$ echo "$(cat $HOME/tmp/demo.txt)"
foo
bar
quux

The new outer quotes retained the newlines; the original replaced newlines with spaces.

The Bash FAQ has more: specif­i­cal­ly Command Substition and Word Splitting.

blog comments powered by Disqus
Review: The Fourth Secret » « Review: Big City, Bad Blood