I have a folder containing two files scrap.sh and data.txt. In the bash script I have the following script
x="$(ls -l)"
echo $x
The output of running this script is all on one line
total 4 -rw-rw-r-- 1 gary gary 0 Feb 9 21:52 data.txt -rw-rw-r-- 1 gary gary 21 Feb 9 22:00 scrap.sh
However, when I change the script to the one-liner
echo "$(ls -l)"
I get this
total 4
-rw-rw-r-- 1 gary gary 0 Feb 9 21:52 data.txt
-rw-rw-r-- 1 gary gary 16 Feb 9 22:01 scrap.sh
Why is there a difference in the output?! The first one produces everything on one line and the next one on two separate lines. Both scripts seem to be functionally the same.
echo "$x"(2) https://www.gnu.org/software/bash/manual/html_node/Word-Splitting.html – dave_thompson_085 Feb 10 '20 at 03:29echo $xinstead ofecho "$x") causes its value to be split into "words" and any of those that contain wildcards to be expanded to a list of matching filenames. You almost never want this, therefore you should (almost always) double-quote your variable references. Oh, and run your scripts through shellcheck.net -- it's good at spotting common mistakes like this. – Gordon Davisson Feb 10 '20 at 05:34