In the following example
for f in *
do
res=$(ls -la "$f")
echo "$res"
done
Is this the correct way to use quotes? I know I should always quote the variable, but is the subshell output implicitly quoted?
The output from command substitution ($()
) is not implicitly quoted:
$ for i in $(echo "foo bar"); do echo $i; done
foo
bar
The loop above splits the unquoted output along words. We can prevent this behavior by quoting the result:
$ for i in "$(echo "foo bar")"; do echo $i; done
foo bar
However, when assigning a variable, as in your example, the result of the subshell is not split, even without quotes:
$ baz=$(echo "foo bar")
$ echo "$baz"
foo bar
Unlike StackOverflow's syntax highlighting, the shell understands quotes inside command substitution, so we don't need to escape nested quotes:
$ baz="foo"
$ echo "$(echo "$baz $(echo "bar")")"
foo bar
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With