Hi,
All script have their difficulties
But I believe this could do it for you.
Code:
#/bin/bash
# Input file is first argument for the script, ex. ./ping.sh file_containing_ip_or_hosts.txt
input_file=$1
# Output file is second argument for the script, ex. ./ping.sh first_file.txt output_file.txt
output_file=$2
# Just gets the date in 2009-02-20 15:20:00 format
date=$(date +"%Y-%m-%d %H:%M:%S")
echo "Starting pings ($date)" > $output_file
# Loops throu the file supplied above
for i in $(cat $input_file); do
# Ping just once since you want to see what they replied and redirect all the output to /dev/null
ping -c1 $i &> /dev/null
# Use the internal error handling from ping to determine the outcome, each line after this is just handling return codes.
case $? in
0) echo "Successfully pinged $i" >> $output_file ;;
1) echo "Failed to ping $i, timed out" >> $output_file ;;
2) echo "Failed to ping $i, Host not found" >> $output_file ;;
*) echo "Failed to ping $i, General failure ($? returncode)" >> $output_file ;;
esac
done
This at the moment will give you information about everything. If you wish just to have the ones that replied you can delete the lines below 0) in the case $?.
$? returns returncode for the success or unsuccess of a program. 0 being successful and every other higher number will be a failure.
If you wish to keep the errors but in another file, you can change the output destination by changing $output_file on the line you wish to send to another file.
Do not set the variable to something else thou, if you do it will fail use it for all other instances that uses that variable.
Code:
case $? in
0) echo "Successfully pinged $i" >> $output_file ;;
1) echo "Failed to ping $i, timed out" >> /path/to/error_file.txt ;;
2) echo "Failed to ping $i, Host not found" >> /path/to/error_file.txt ;;
*) echo "Failed to ping $i, General failure ($? returncode)" >> /path/to/error_file.txt ;;
esac
This is a more proper way to change it. But you could also do a "error_log=/path/to/file.txt" and set it to $error_log instead.
Best regards
Fredrik Eriksson