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.
#!/bin/bash
ret1=`./a.sh` &
ret2=`./b.sh`
if [ "${ret1}"="" -a "${ret2}"="" ]; then
sleep 1
else
echo ${ret1},${ret2}
end
#!/bin/bash
sleep 10
echo 1
#!/bin/bash
sleep 5
echo 2
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With