Issue
So, I'm working on a bash script on a Linux VM for a class that pings multiple ip addresses from an input file and emails myself if there is any errors, while sending the results (successful or failed) to an output log. To get full credit we need to have it run every 5 minutes using cron. If I run it manually with the bash command, it works fine, doing all of the things it is supposed to do, but when it runs with cron I receive this error:
/home/kali/Documents/GitHub/BFOR206/hw1.sh: line 33: hw1_input.txt: No such file or directory
Here is my code:
#!/bin/bash
# File path for input (ip addresses)
hw1_input="~/Documents/GitHub/BFOR206/hw1_input.txt"
# Loop through and read each address in the file
while read -r address; do
# Ping the address and save the output
ping -c 1 $address > /dev/null
# Check if ping was normal or failed
if [ $? -eq 0 ]; then
# If the ping is normal, log to a file
echo "Ping successful for $address at $(date)" >> hw1_output.log
else
# If the ping failed. log the error to a file
echo "Ping failed for $address at $(date)" >> hw1_output.log
# Send an email notification to self about error
echo "Ping failed for $address at $(date)" | mail -s "Ping Error!" kali@kali
fi
done < "hw1_input.txt"
The error is from the last line.
I'm very new to scripting so if anyone has any ideas of ways I can try and fix this, please try and explain it in simple terms. I've spent countless hours already trying to troubleshoot it myself so posting here is kind of my last resort.
If it helps, this is the script I am using to run the cron:
*/5 * * * * bash ~/Documents/GitHub/BFOR206/hw1.sh
Solution
Two problems:
- Quoting the pathname prevents bash from expanding
~
into your home directory. Don't quote in the assignment tohw1_input
. - You don't have the directory path in the filename you're redirecting from. You should use the
hw1_input
variable.
#!/bin/bash
# File path for input (ip addresses)
hw1_input=~/Documents/GitHub/BFOR206/hw1_input.txt
# Loop through and read each address in the file
while read -r address; do
# Ping the address and save the output
ping -c 1 $address > /dev/null
# Check if ping was normal or failed
if [ $? -eq 0 ]; then
# If the ping is normal, log to a file
echo "Ping successful for $address at $(date)" >> hw1_output.log
else
# If the ping failed. log the error to a file
echo "Ping failed for $address at $(date)" >> hw1_output.log
# Send an email notification to self about error
echo "Ping failed for $address at $(date)" | mail -s "Ping Error!" kali@kali
fi
done < "$hw1_input"
Answered By - Barmar Answer Checked By - Robin (WPSolving Admin)