How to wait in bash script to subprocess and if one of them return exit code 1 so I want to stop all subprocess.
This is what I tried to do. But there are a some of issues:
If the first process is longer than all the others, and another process fails in the background ... then the script waits for the first process to finish, even though another process has already failed.
Can't detect that doSomething failed because I use pipe for the desired print format.
#!/bin/bash
function doSomething()
{
echo [ $1 start ]
sleep $1
if [ $1 == 10 ]; then
failed
fi
echo [ sleep $1 ]: done
}
function failed(){
sleep 2
echo ------ process failed ------
exit 1
}
function process_log() {
local NAME=$1
while read Line; do
echo [Name ${NAME}]: ${Line}
done
}
pids=""
(doSomething 4 | process_log 4)&
pids+="$! "
(doSomething 17 | process_log 17)&
pids+="$! "
(doSomething 6 | process_log 6)&
pids+="$! "
(doSomething 10 | process_log 10)&
pids+="$! "
(doSomething 22 | process_log 22)&
pids+="$! "
(doSomething 5 | process_log 5)&
pids+="$! "
for pid in $pids; do
wait $pid || (pkill -P $$ ; break)
done
echo done program
Anyone have an idea?