I am writing a script where I take IP adresses from netstat, and based on those I want to run a specific command for each IP. This command connects to the IP and outputs some text in the terminal. If the command cannot connect it will timeout after around 35 seconds, which makes the script slow.
Here is what I am trying to do: Get the IP adresses from netstat and piping them onward - done For each IP address, run a command, like "mycommand $IP" but run it in paralell. After X seconds, kill all the PIDs of the commands.
Here on stackoverflow I found a script that does this.
#!/bin/bash
for cmd in "$@"; do {
echo "Process \"$cmd\" started";
$cmd & pid=$!
PID_LIST+=" $pid";
} done
echo "Parallel processes have started";
sleep 5
for id in $PID_LIST
do
kill $id
done
echo
echo "All processes have completed";
And it works if you use it like:
./paralell.sh "mycommand 1.1.1.1" "mycommand 2.2.2.2" "mycommand 3.3.3.3"
The trouble I am having is how to get the piped input that looks like this
mycommand 1.1.1.1
mycommand 2.2.2.2
mycommand 3.3.3.3
Into the above script.
It all needs to be on one line as well, cannot use a stored script.
What I have tried:
Replacing the for loop with a while loop, like
myoutput | while read cmd; do... (and the rest of the script above on one line)
However it seems that when I use a while loop instead of the for loop, the $PID_LIST doesnt survive outside of the while loop. As its empty outside I cannot kill the processes after 20 seconds.
Do a while loop spawn a new sub-shell in another matter than the for loop? Or have I done something else when I replaced it?