I am trying to create a ping sweeper and the code never exits properly. However, when I add a wait after the done it exits and is so much faster. Why is that so?
for ip in {200..254} ; do
ping -c 1 "192.168.16.${ip}" |grep "bytes from" |cut -d" " -f 4|cut -d":" -f1 &
done
wait
In your for loop you are running the ping jobs in background via the
&operator at the end of the line. This allows to ping all hosts in parallel instead of doing them one by one.On the other hand, running them in background means that at the moment when the for loop has ended, all ping processes have been spawned but they have not been finished already. Without the
waitthere wouldn't be more statements to execute, the script would exit and those ping processes would end up as orphan processes. Those will be picked up by your init process (pid 1), who will be their new parent process.If you put the
waitafter the for loop, the script will wait for all the child processes to finish and obtain their exit status. This is clean, efficient and should be used.PS: You are using the UNIX filters
grepandcutmultiple times in a pipe:Consider to use
awkinstead, which allows to perform those operations in one run: