Shell – echo variable with content from command substitution

command-substitutionechoquotingshell

I wrote a very basic script of command substitution which is below:

#!/bin/bash
files=$(ls *.fastq);
echo $files

The directory contains bunch of .fastq file and I just want to use echo command to output them

The above sript outputs fastq files with a space between each fastq filename.

When I use it in this way

#!/bin/bash
files=$(ls *.fastq);
echo "$files"

it prints the results on new lines.

Why is it so? Is it something to do with command substitution?

Thanks

Best Answer

When referencing a variable, it is generally advisable to enclose its name in double quotes. This prevents reinterpretation of all special characters within the quoted string -- except $, ` (backquote), and \ (escape). Keeping $ as a special character within double quotes permits referencing a quoted variable ("$variable"), that is, replacing the variable with its value.

Use double quotes to prevent word splitting. An argument enclosed in double quotes presents itself as a single word, even if it contains whitespace separators.

e.g.

variable1="a variable containing five words"
COMMAND This is $variable1    # Executes COMMAND with 7 arguments:
# "This" "is" "a" "variable" "containing" "five" "words"

COMMAND "This is $variable1"  # Executes COMMAND with 1 argument:
# "This is a variable containing five words"

Enclosing the arguments to an echo statement in double quotes is necessary only when word splitting or preservation of whitespace is an issue.

For more info and examples go here

Related Question