Heredoc within command substitution: error when qu

2019-07-03 21:33发布

Consider the following obfuscated script intended for printing a single quote, which works on ksh:

#!/bin/ksh
echo "$(cat <<EOF
'
EOF
)"

Output:

'

However, when I run the same script with bash 3.2.51(1) on OS X,

#!/bin/bash
echo "$(cat <<EOF
'
EOF
)"

bash reports the following errors:

./heredoc-within-cmdsubst: line 3: unexpected EOF while looking for matching `''
./heredoc-within-cmdsubst: line 6: syntax error: unexpected end of file

And run with zsh 5.0.2,

#!/bin/zsh
echo "$(cat <<EOF
'
EOF
)"

zsh reports the following error:

./heredoc-within-cmdsubst:6: unmatched "

Similar errors occur when the single quote is replaced by a double quote or parenthesis. If I balance the single quote/double quote/parenthesis with a matching single quote/double quote/parenthesis, then the script runs fine with both bash and zsh.

Is this issue just a bug in (the relevant versions of) bash and zsh, or are there any syntactic rules violated here?

标签: bash shell zsh
1条回答
手持菜刀,她持情操
2楼-- · 2019-07-03 22:17

I would consider this a parsing bug until/unless the developers say otherwise. The code works in dash as-is, and there is a similar unclosed-quote error in this zsh question.

UPDATE: This is actually fixed in bash 4.1; I only checked in zsh 5.0.2 (the latest version is 5.0.6).

查看更多
登录 后发表回答