Bash tries to execute commands in heredoc

和自甴很熟 提交于 2019-12-06 06:13:31

问题


I am trying to write a simple bash script that will print a multiline output to another file. I am doing it through heredoc format:

#!/bin/sh

echo "Hello!"
cat <<EOF > ~/Desktop/what.txt
a=`echo $1 | awk -F. '{print $NF}'`
b=`echo $2 | tr '[:upper:]' '[:lower:]'`
EOF

I was expecting to see a file in my desktop with these contents:

a=`echo $1 | awk -F. '{print $NF}'`
b=`echo $2 | tr '[:upper:]' '[:lower:]'`

But instead, I am seeing these as the contents of my what.txt file:

a=
b=

Somehow, even though it is part of a heredoc, bash is trying to execute it line by line. How do I prevent this, and print the contents to the file as it is?


回答1:


Quote EOF so that bash takes inputs literally:

cat <<'EOF' > what.txt
a=`echo $1 | awk -F. '{print $NF}'`
b=`echo $2 | tr '[:upper:]' '[:lower:]'`
EOF

Also start using $() for command substitution instead of old and problematic ``.



来源:https://stackoverflow.com/questions/34380315/bash-tries-to-execute-commands-in-heredoc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!