How to spawn a background process in a bash script

For example, I want to spawn many ssh background processes in one bash script:

for i in `cat ./all-hosts`
do
    ssh $i "ifconfig | grep Link"
done

Simply adding a & to the ssh commands does not work.

Here is the script that works:

for i in `cat ./all-hosts`
do
    ssh $i "ifconfig | grep Link" &
done

Or in one command

for i in `cat ./all-hosts`; do ssh $i "ifconfig | grep Link" & done

What is needed is to create a subshell.

Answered by anonymous.

The makes many processes run in parallel.

To wait for all processes to exit to continue next step:

wait

For the above script:

for i in `cat ./all-hosts`
do
    ssh $i "ifconfig | grep Link" &
done

wait
# continue for next steps

Leave a Reply

Your email address will not be published. Required fields are marked *