0

I am trying to get a the script to ping a series of host ip's.

The first script works fine, but only outputs one ping at a time whereas I would prefer to do this simultaneously. The second script I added job control to try do the jobs in parallel however the script instantly outputs that everything is alive.

First bash:

#!/bin/bash
hostfile=config/hosts.txt

counter0=0
counter1=0

while IFS=',' read -r hostname ip_address; do
    ip_address=$(echo "$ip_address" | sed 's/[^[:print:]]//')
    if ping -c 1 "$ip_address" &> /dev/null; then
        # The device is alive
        echo -e "$hostname (\e]8;;http://$ip_address\a$ip_address\e]8;;\a) is alive"
        ((counter0++))
    else
        # The device is not alive
        echo -e "$hostname (\e]8;;http://$ip_address\a$ip_address\e]8;;\a) is not responding"
        ((counter1++))
    fi
done < "$hostfile"

echo $counter0 hosts alive!
echo $counter1 not responding.```

Second bash:

#!/bin/bash
hostfile=config/hosts.txt

counter0=0
counter1=0

while IFS=',' read -r hostname ip_address; do
    ip_address=$(echo "$ip_address" | sed 's/[^[:print:]]//')
    if ping "$ip_address" &>/dev/null 2>&1 & then
        # The device is alive
        echo -e "$hostname (\e]8;;http://$ip_address\a$ip_address\e]8;;\a) is alive" &
        ((counter0++))
    else
        # The device is not alive
        echo "$hostname ($ip_address) is not responding" &
        ((counter1++))
    fi
done < "$hostfile"

wait
echo $PATH
echo $counter0 hosts alive!
echo $counter1 not responding.```

Has anyone got any idea's as to why the second script is not working?

  • 1
    Running a process in the background always succeeds (unless your OS has serious resource starvation problems) - you are not checking whether `ping` succeeds, only whether it actually started running; and indeed, you cannot know whether it succeeded until it finishes. – tripleee May 03 '23 at 08:15

0 Answers0