0

我正在尝试使用 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
4

1 回答 1

2

双引号内的某些内容仍会被评估,例如:

echo "Current_IP=$(host $HOSTNAME | cut -f4 -d' ')" >> /etc/no-ip.sh

在这里,$(...)结构被评估。所以你想在整个事情周围使用单引号:

echo 'Current_IP=$(host $HOSTNAME | cut -f4 -d" ")' >> /etc/no-ip.sh

其他行也类似。


也就是说,heredoc可能是写这个的更好方法。您需要引用定界符字符串以使正文按字面意思解释:

cat <<'EOF' > /etc/no-ip.sh
...
EOF
于 2013-04-20T20:15:28.620 回答