I just can't get the code below to work.
Code:
#!/bin/bash
ip=$1
first=$2
last=$3
if (( $first >= 1 && $first <= 255 && $last >= 1 && $last <= 255 && $first <= $last)); then
range=0
else
range=1
fi
if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0]$ ]]; then
OIFS=$IFS
IFS='.'
ip=($ip)
IFS=$OIFS
[[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
&& ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
VIP=0
else
VIP=1
fi
if (( $range == 0 && $VIP == 0)); then
echo "intiating ping scan for $1 $first-$last"
echo ""
echo "==================================================="
for i in $(seq $first $last); do ping -c 1 ${ip[0]}.${ip[1]}.${ip[2]}.$i > /dev/null;done
if [ $? -eq 0 ]; then
echo "${ip[0]}.${ip[1]}.${ip[2]}.$i is up"
else
echo "${ip[0]}.${ip[1]}.${ip[2]}.$i is down"
fi
else
echo "invalid IP or range"
echo "=================================================="
echo "Usage: ./ping_scan.sh <ip[must end in 0]{ex. 192.168.5.0}> "
echo "<start address {ex. 23}> <end address {ex. 254}>"
fi
The issue revolves around this code snippet:
if (( $range == 0 && $VIP == 0)); then
echo "initiating ping scan for $1 $first-$last"
echo ""
echo "==================================================="
for i in $(seq $first $last); do ping -c 1 ${ip[0]}.${ip[1]}.${ip[2]}.$i > /dev/null;done
if [ $? -eq 0 ]; then
echo "${ip[0]}.${ip[1]}.${ip[2]}.$i is up"
else
echo "${ip[0]}.${ip[1]}.${ip[2]}.$i is down"
fi
else
echo "invalid IP address or range"
echo "=================================================="
echo "Usage: ./ping_scan.sh <ip[must end in 0]{ex. 192.168.5.0}> "
echo "<start address {ex. 23}> <end address {ex. 254}>"
fi
I used set -x
to confirm my suspicions. The issue I am having is I am only receiving output from the last IP address that is being pinged.
The for
loop is running for each IP address, completing, getting $? for the last IP address pinged, and then the script is moving into the if
statement and printing the status of the final IP address.
I need the for
loop to run for each IP address and the if
statement to run for each IP address and output the status of each. I know this can be done, and I have tried multiple configurations, but none seem to work.
How can I fix it?