I have this script I am working but cant seem to get it to send an email. I have a bash debug going but the script doesn't seem to be executing the mail command. Any help would be greatly appreciated. I have the email variable set as such
echo "Please enter email address"
read -r var2
and I have the email variable set as
EMAIL="$var2"
The script creates the log file that cat uses, and it seems to do everything I need "except" send the email. The part that does the work is below.
while true;
do
cat ip_monitor_list.txt | while read IP
do
fping -c 1 -q "$IP" > /dev/null
if [ $? -eq 0 ]; then
STATUS=$(cat $LOG."$IP")
if [ "$STATUS" != "$IP-UP!" ]; then
echo "$(date): ping OK, $IP host is UP!" |
mail -s "$IP host is UP!" "$EMAIL"
fi
echo "$IP-UP!" > $LOG.$IP
I also have an "else statement very similar to the above but to do the same thing if it is down. I noticed if I try the mail command by itself just typing it out in the terminal linux$mail -s "subject" myemail@blah.com, it works. But if I paste the below directly in the terminal like below
echo "$(date): ping Failed, $IP host is DOWN!" | mail -s "$IP host is DOWN!" myemail@blah.com
I get -bash: !": event not found
Thanks again for any help I really appreciate it.
Here is the updated version in its entirety.
#!/bin/bash
exec 5> debug_output.txt
BASH_XTRACEFD="5"
PS4='$line0: '
set -x
trap "exit" INT
echo "Please enter time in seconds:"
read -r var1
echo "Please enter email address"
read -r var2
LOG=mylog.log
SECONDS="$var1"
EMAIL="$var2"
#Array to write IP's pasted to ip_monitor_list.txt file.
arrIP=()
echo "Enter the IP addresses here enter and Ctrl-d when finished :"
while read IP
do
arrIPAddress+=($IP)
echo "$IP" >> ip_monitor_list.txt
echo "$IP-UP\!" > $LOG.$IP
done
while true;
do
cat ip_monitor_list.txt | while read IP
do
fping -c 1 -q "$IP" > /dev/null
if [ $? -eq 0 ]; then
STATUS=$(cat $LOG."$IP")
if [ "$STATUS" != "$IP-UP\!" ]; then
echo "$(date): ping OK, $IP host is UP\!" |
mail -s "$IP host is UP\!" "$EMAIL"
fi
echo "$IP-UP\!" > $LOG.$IP
else
STATUS=$(cat $LOG."$IP")
if [ "$STATUS" != "$IP-DOWN\!" ]; then
echo "$(date): ping Failed, $IP host is DOWN\!" |
mail -s "$IP host is DOWN\!" "$EMAIL"
fi
echo "$IP-DOWN\!" > $LOG.$IP
fi
done
sleep $SECONDS
DONE
#File cleanup
rm ip_monitor_list.txt