Bash 脚本 - Cat EOF 破坏
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16124666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash Script - Cat EOF breaking
提问by John Nguyen
I'm attempting to use cat EOF to write a bash script to automatically install a cron script, this part is breaking the script and I'm not sure where I am going wrong. For some reason the script is running these commands before echoing them to /etc/no-ip.sh
我正在尝试使用 cat EOF 编写一个 bash 脚本来自动安装一个 cron 脚本,这部分正在破坏脚本,我不确定我哪里出错了。出于某种原因,脚本在将这些命令回显到 /etc/no-ip.sh 之前运行这些命令
echo "#!/bin/sh" >> /etc/no-ip.sh
echo "HOSTNAME=hostname" >> /etc/no-ip.sh
echo "LOGFILE=no-ip-log" >> /etc/no-ip.sh
echo " " >> /etc/no-ip.sh
echo "Current_IP=$(host $HOSTNAME | cut -f4 -d' ')" >> /etc/no-ip.sh
echo " " >> /etc/no-ip.sh
echo "if [ ! -s $LOGFILE ] ; then" >> /etc/no-ip.sh
echo "echo "sshd : $Current_IP : allow" >> /etc/hosts.allow" >> /etc/no-ip.sh
echo "echo $Current_IP > $LOGFILE" >> /etc/no-ip.sh
echo "else" >> /etc/no-ip.sh
echo " " >> /etc/no-ip.sh
echo "Old_IP=`head -n 1 /etc/no-ip-log`" >> /etc/no-ip.sh
echo " " >> /etc/no-ip.sh
echo "if [ "$Current_IP" = "$Old_IP" ] ; then" >> /etc/no-ip.sh
echo "echo IP address has not changed" >> /etc/no-ip.sh
echo "else" >> /etc/no-ip.sh
echo "sed -i 's/'$Old_IP'/'$Current_IP'/' /etc/hosts.allow" >> /etc/no-ip.sh
echo "echo $Current_IP > $LOGFILE" >> /etc/no-ip.sh
echo "echo iptables have been updated" >> /etc/no-ip.sh
echo "fi" >> /etc/no-ip.sh
echo "fi" >> /etc/no-ip.sh
echo "EOF" >> /etc/no-ip.sh
回答by Thomas
Some things inside double quotes still get evaluated, such as:
双引号内的一些内容仍然会被评估,例如:
echo "Current_IP=$(host $HOSTNAME | cut -f4 -d' ')" >> /etc/no-ip.sh
Here, the $(...)construct is evaluated. So you want to use single quotes around the entire thing:
在这里,$(...)评估构造。所以你想在整个事情周围使用单引号:
echo 'Current_IP=$(host $HOSTNAME | cut -f4 -d" ")' >> /etc/no-ip.sh
And similar for the other lines.
其他线路也类似。
That said, a heredocis probably a better way to write this. You'll need to quote your delimiter string to get the body to be interpreted literally:
也就是说,heredoc可能是更好的写法。您需要引用分隔符字符串才能按字面意思解释正文:
cat <<'EOF' > /etc/no-ip.sh
...
EOF

