2013-04-20 125 views
0

我試圖用貓EOF編寫一個bash腳本來自動安裝一個cron腳本,這部分是打破腳本,我不知道我要去哪裏錯了。出於某種原因,該腳本呼應之前運行這些命令/etc/no-ip.shBash腳本 - 貓EOF打破

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 

回答

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 
+0

謝謝!!!!!!我一直試圖使用貓,並沒有意識到'EOF'是一種選擇。爲什麼引用分隔符字符串會強制字面解釋正文? – 2013-04-20 20:47:15

+0

這就是bash編碼的方式。請參閱我鏈接到的頁面中的示例19-7。 – Thomas 2013-04-21 08:12:42