The previous script tests each address sequentially. The delay for each test is accumulated and becomes large. Running the ping commands in parallel will make this faster. Enclosing the body of the loop in {}& will make the ping commands run in parallel. ( ) encloses a block of commands to run as a subshell, and & sends it to the background:
#!/bin/bash
#Filename: fast_ping.sh
# Change base address 192.168.0 according to your network.
for ip in 192.168.0.{1..255} ;
do
(
ping $ip -c2 &> /dev/null ;
if [ $? -eq0 ];
then
echo $ip is alive
fi
)&
done
wait
In the for loop, we execute many background processes and come out of the loop, terminating the script. The wait command prevents the script from terminating until all its child processes have exited.
The output will be in the order that pings reply. This will not be the numeric order in which they were sent if some machines or network segments are slower than others.