echo variable with content from command substitution
You have newlines because ls
puts them on separate lines. The newlines disappear without the quotes because the shell (bash) passes each unquoted space separated text to the command as a separate argument.
Note: The command substitution is done by the shell, not by ls
, so you do not need ls
.
Therefore you can do
#!/bin/bash
echo *.fastq
or
#!/bin/bash
files="*.fastq"
echo "$files"
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