Search code examples
bashheredocubuntu-22.04

bash - here-document - problems with special characters together with double quotes despite the "repr"


Positive case:

set -- 'no " tabs' 'tab and double quotes   "'
repr="$(printf -- '%q ' "$@")"
echo "$repr"

Output:

no\ \"\ tabs $'tab and double quotes\t"'

Negative case:

bash -s <<- EOF
    repr="$(printf -- '%q ' "$@")"
    echo "\$repr"
EOF

Output:

bash: line 1: unexpected EOF while looking for matching `''
bash: line 3: syntax error: unexpected end of file

Why?

EDIT: I need to keep parameter expansion enabled because in here-doc I also need to pass functions, terminal options and execute variables as commands.


Solution

  • One way to get the same result is to quote EOF :

    set -- 'no " tabs' 'tab and double quotes   "'
    bash -s "$@" <<-'EOF'
        repr="$(printf -- '%q ' "$@")"
        echo "$repr"
    EOF