简体   繁体   中英

Parameter substitution in input redirection

I'm a newbie to shell scripting and I have the following problem:

If I enter into the shell

cat << EOF
'"$10^2$"'
EOF

I expected (and wanted) to get something like

"$10^2$"

but actually it used parameter substitution and I got

'"0^2"'

Why does it parameter substitution (I used single quotes!?)? And how can I get the desired output?

Escape the dollar sign:

cat << EOF
'"\$10^2$"'
EOF

OUTPUT:

"$10^2$"

Otherwise $1 is being expanded by shell and shows output as empty string only only and you get output as '"0^2$"'

UPDATE: Otherwise use this form of heredoc to avoid variable expansion:

cat <<'EOF'
'"$10^2$"'
EOF
'"$10^2$"'

Explanation: As per man bash:

<<[-]word
    here-document
delimiter

No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. In the latter case, the character sequence \\ is ignored, and \\ must be used to quote the characters \\, $, and `.

See bolded text above for the explanation why variables got expanded in your example but not when I used quoted 'EOF' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM