Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute multiple shell scripts concurrently

I want to do the following things:

  • Execute multiple shell scripts (here 2 scripts) concurrently.

  • Wait until both scripts finish

  • Dump return value of each script

However, main.sh does not work as expected.


main.sh

#!/bin/bash

ret1=`./a.sh` &
ret2=`./b.sh`

if [ "${ret1}"="" -a "${ret2}"="" ]; then
   sleep 1
else
   echo ${ret1},${ret2}
end

a.sh

#!/bin/bash
sleep 10
echo 1

b.sh

#!/bin/bash
sleep 5
echo 2
like image 448
akry Avatar asked Nov 23 '11 17:11

akry


People also ask

Can shell execute multiple shell scripts concurrently?

GNU parallel is a shell tool for executing jobs in parallel using one or more computers. A job can be a single command or a small script that has to be run for each of the lines in the input. The typical input is a list of files, a list of hosts, a list of users, a list of URLs, or a list of tables.

How do I run multiple shell commands in one line?

Windows. On Windows you can use a single ampersand (&) or two ampersands (&&) to separate multiple commands on one command line. When a single ampersand is used, cmd.exe runs the first command, and then the second command.


2 Answers

Here is some code that I have been running, that seems to do exactly what you want. Just insert ./a.sh and ./b.sh where appropriate:

# Start the processes in parallel...
./script1.sh 1>/dev/null 2>&1 &
pid1=$!
./script2.sh 1>/dev/null 2>&1 &
pid2=$!
./script3.sh 1>/dev/null 2>&1 &
pid3=$!
./script4.sh 1>/dev/null 2>&1 &
pid4=$!

# Wait for processes to finish...
echo -ne "Commands sent... "
wait $pid1
err1=$?
wait $pid2
err2=$?
wait $pid3
err3=$?
wait $pid4
err4=$?

# Do something useful with the return codes...
if [ $err1 -eq 0 -a $err2 -eq 0 -a $err3 -eq 0 -a $err4 -eq 0 ]
then
    echo "pass"
else
    echo "fail"
fi

Note that this captures the exit status of the script and not what it outputs to stdout. There is no easy way of capturing the stdout of a script running in the background, so I would advise you to use the exit status to return information to the calling process.

like image 119
Lee Netherton Avatar answered Oct 05 '22 00:10

Lee Netherton


The answer you seek is in this question shell - get exit code of background process

Basically, when you background a process you can't get its exit code directly. But if you run the bash wait command, then wait's exit code will return the exit code of the background process.

./a.sh &
pid1=$!
./b.sh
ret2=$?
wait ${pid1}
ret1=$?

This will work even if a.sh ends before you run wait. The special variable $? holds the exit code of the previous process. And $! holds the Process ID of the previously run process.

like image 45
Michael Dillon Avatar answered Oct 05 '22 01:10

Michael Dillon