Bash Parallel Execution

If you have ever wanted an easy way to execute multiple jobs in parallel in bash, then this is the snippet for you. This was originally posted on Stack Exchange. It has been modified a bit.


#how many jobs to run at one time

# The bgxupdate and bgxlimit functions below allow for
# running X jobs in parallel in bash.  They are taken from:

# bgxupdate - update active processes in a group.
#   Works by transferring each process to new group
#   if it is still active.
# in:  bgxgrp - current group of processes.
# out: bgxgrp - new group of processes.
# out: bgxcount - number of processes in new group.

bgxupdate() {
    ((bgxcount = 0))
    bgxjobs=" $(jobs -pr | tr '\n' ' ')"
    for bgxpid in ${bgxoldgrp} ; do
        echo "${bgxjobs}" | grep " ${bgxpid} " >/dev/null 2>&1
        if [[ $? -eq 0 ]] ; then
            bgxgrp="${bgxgrp} ${bgxpid}"
            ((bgxcount = bgxcount + 1))

# bgxlimit - start a sub-process with a limit.

#   Loops, calling bgxupdate until there is a free
#   slot to run another sub-process. Then runs it
#   an updates the process group.
# in:  $1     - the limit on processes.
# in:  $2+    - the command to run for new process.
# in:  bgxgrp - the current group of processes.
# out: bgxgrp - new group of processes

bgxlimit() {
    bgxmax=$1 ; shift
    while [[ ${bgxcount} -ge ${bgxmax} ]] ; do
        sleep 1
    if [[ "$1" != "-" ]] ; then
        $* &
        bgxgrp="${bgxgrp} $!"

for LINE in `cat hosts`
    CHECK_SCRIPT='echo $(hostname),$(cat /etc/debian_version)'
    bgxlimit $JOBS_AT_ONCE ssh ${LINE} "${CHECK_SCRIPT}"
# Wait until all queued processes are done.

while [[ ${bgxcount} -ne 0 ]] ; do
    while [[ ${oldcount} -eq ${bgxcount} ]] ; do
        sleep 1

In this script the primary changes are defining the max number of simultaneous jobs, as well as doing somewhat useful work in returning the hostname and the debian version.


3 thoughts on “Bash Parallel Execution

  1. I am trying to figure out what bgx can do that you cannot do by using GNU Parallel (10 seconds installation: wget -O – | sh).

    It seems your example could be written:

    cat hosts | parallel -q -j 20 ssh {} echo ‘$(hostname),$(cat /etc/debian_version)’


    parallel –slf hosts -j 20 –nonall echo ‘$(hostname),$(cat /etc/debian_version)’

      • But that is exactly my point: If you are able to write in your homedir then ‘wget -O – | sh’ will install it in 10 seconds. You do not need write permission anywhere else.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s