Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash, is subshell output implicitly quoted

Tags:

linux

bash

shell

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?

like image 908
Tuomas Toivonen Avatar asked Sep 23 '17 06:09

Tuomas Toivonen


Video Answer


1 Answers

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
like image 184
Cy Rossignol Avatar answered Sep 21 '22 12:09

Cy Rossignol