John Nguyen
John Nguyen

Reputation: 41

Bash Script - Cat EOF breaking

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

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

Upvotes: 1

Views: 16739

Answers (1)

Thomas
Thomas

Reputation: 182000

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 heredoc is probably a better way to write this. You'll need to quote your delimiter string to get the body to be interpreted literally:

cat <<'EOF' > /etc/no-ip.sh
...
EOF

Upvotes: 3

Related Questions