Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

Tags:

bash

process

wait

How to wait in a bash script for several subprocesses spawned from that script to finish, and then return exit code !=0 when any of the subprocesses ends with code !=0?

Simple script:

#!/bin/bash for i in `seq 0 9`; do   doCalculations $i & done wait 

The above script will wait for all 10 spawned subprocesses, but it will always give exit status 0 (see help wait). How can I modify this script so it will discover exit statuses of spawned subprocesses and return exit code 1 when any of subprocesses ends with code !=0?

Is there any better solution for that than collecting PIDs of the subprocesses, wait for them in order and sum exit statuses?

like image 526
tkokoszka Avatar asked Dec 10 '08 13:12

tkokoszka


People also ask

How do I make bash script wait?

How to Use the Bash Sleep Command. Sleep is a very versatile command with a very simple syntax. It is as easy as typing sleep N . This will pause your script for N seconds, with N being either a positive integer or a floating point number.

Does bash wait for command to finish before executing next?

The bash WAIT command is used to halt the execution of a script until all background jobs or specified JobID/PIDs terminate successfully and return an expected exit code to trigger the next command that was “waited for.”

What does exit code 0 mean in bash?

A successful command returns a 0, while an unsuccessful one returns a non-zero value that usually can be interpreted as an error code. Well-behaved UNIX commands, programs, and utilities return a 0 exit code upon successful completion, though there are some exceptions.

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.


1 Answers

wait also (optionally) takes the PID of the process to wait for, and with $! you get the PID of the last command launched in the background. Modify the loop to store the PID of each spawned sub-process into an array, and then loop again waiting on each PID.

# run processes and store pids in array for i in $n_procs; do     ./procs[${i}] &     pids[${i}]=$! done  # wait for all pids for pid in ${pids[*]}; do     wait $pid done 
like image 107
Luca Tettamanti Avatar answered Oct 16 '22 21:10

Luca Tettamanti