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.


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

One comment:

  1. From ABS guide:

    Running a shell script launches a new process, a subshell.

    Definition: A subshell is a child process launched by a shell (or shell script).

    A subshell is a separate instance of the command processor — the shell that gives you the prompt at the console or in an xterm window. Just as your commands are interpreted at the command-line prompt, similarly does a script batch-process a list of commands. Each shell script running is, in effect, a subprocess (child process) of the parent shell.

    A shell script can itself launch subprocesses. These subshells let the script do parallel processing, in effect executing multiple subtasks simultaneously.

Leave a Reply

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