Home > front end >  bash - here-document - problems with special characters together with double quotes despite the &quo
bash - here-document - problems with special characters together with double quotes despite the &quo

Time:01-02

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.

CodePudding user response:

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

CodePudding user response:

If you look at what exactly the output of the here-doc is, with

cat -t <<- EOF
    repr="$(printf -- '%q ' "$norepr")"
    echo "\$repr"
EOF

you get this output:

    repr="$'tab and double quotes\t"' "
    echo "$repr"

Now, if you look at the first epxression:

repr="$'tab and double quotes\t"' "

you'll notice that these are unbalanced quotes:

repr="$'tab and double quotes\t"' "
     │││                      │││ │
     │└┴ literal $, ', and \t ┘││ │
     └──── syntactical " ──────┘│ │
        unclosed syntactical ' ─┘ │
                     literal " ───┘

For a simpler example, consider this:

$ a="$'abc\t'"
$ declare -p a
declare -- a="\$'abc\\t'"

CodePudding user response:

@Philippe Thank you, I have solved it!

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

Output:

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