Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash & (ampersand) operator

I'm trying to run 3 commands in parallel in bash shell:

$ (first command) & (second command) & (third command) & wait

The problem with this is that if first command fails, for example, the exit code is 0 (I guess because wait succeeds).

The desired behavior is that if one of the commands fails, the exit code will be non-zero (and ideally, the other running commands will be stopped).

How could I achieve this?

Please note that I want to run the commands in parallel!

like image 467
Misha Moroshko Avatar asked Feb 13 '12 09:02

Misha Moroshko


People also ask

What does bash mean?

As explained in the Bash Reference Manual, the name bash is an acronym of "Bourne-again SHell" which is a pun on Stephen Bourne, author of the Bourne shell. Bash is a superset of the earlier shell, and generally compatible with Bourne shell programs.

What is bash used for?

Bash or Shell is a command line tool that is used in open science to efficiently manipulate files and directories.

Is bash a Windows or Linux?

Bash was one of the first programs Linus Torvalds ported to Linux, alongside GCC. A version is also available for Windows 10 via the Windows Subsystem for Linux. It is also the default user shell in Solaris 11.

Is bash a language?

Bash is a powerful programming language, one perfectly designed for use on the command line and in shell scripts. This three-part series explores using Bash as a command-line interface (CLI) programming language.


2 Answers

the best I can think of is:

first & p1=$!
second & p2=$!
...

wait $p1 && wait $p2 && ..

or

wait $p1 || ( kill $p2 $p3 && exit 1 )
...

however this still enforces an order for the check of processes, so if the third fails immediately you won't notice it until the first and second finishes.

like image 78
Karoly Horvath Avatar answered Nov 13 '22 15:11

Karoly Horvath


This might work for you:

parallel -j3 --halt 2 <list_of_commands.txt

This will run 3 commands in parallel.

If any running job fails it will kill the remaining running jobs and then stop, returning the exit code of the failing job.

like image 25
potong Avatar answered Nov 13 '22 15:11

potong