nested double quotes in highly-voted one-liner

Once one is inside $(...), quoting starts all over from scratch.

In other words, "..." and $(...) can nest within each other. Process substitution, $(...), can contain one or more complete double-quoted strings. Also, double-quoted strings may contain one or more complete process substitutions. But, they do not interlace. Thus, a double-quoted string that starts inside a process substitution will never extend outside of it or vice versa.

So, consider:

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

Inside the inner $(...) is:

dirname "${BASH_SOURCE[0]}"

In the above ${BASH_SOURCE[0]} is double-quoted. Any quotes, double or single, outside of the $(...) are irrelevant when determining that ${BASH_SOURCE[0]} is double-quoted.

The outer $(...) contains:

cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd

Here, the expression $( dirname "${BASH_SOURCE[0]}" ) is double-quoted. The fact that there are quotes outside of the outer $(...) is irrelevant when considering what is inside it. The fact that there are quotes inside the inner $(...) is also irrelevant.

Here is how the double-quotes match up:

enter image description here


Your puzzle isn't right about how bash (and the shell in general) parsed the input. In:

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

First, bash parse the right hand side of assignment to one long string $( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) because double quote can appear inside double quotes.

After then, bash start parsing the command substitution. Because all characters following open parenthesis to enclosing parenthesis are used to construct the command inside command substitution, you will get:

cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd

The shell continue parsing that compound command, break it into two parts:

  • cd "$( dirname "${BASH_SOURCE[0]}" )"
  • pwd

Then applying the same parsing rule for cd "$( dirname "${BASH_SOURCE[0]}" )", but this time, double quotes are not redundant, but make sense. They prevent field splitting on result of $( dirname "${BASH_SOURCE[0]}" ), and also the expansion of ${BASH_SOURCE[0]} (In contrast with the outer most double quotes, will are not necessary in RHS of variable assignment to prevent split+glob).


This rule apply to command substitution in all POSIX shell. A more details puzzle you can read in Token Recognition section of POSIX spec.