-
-
Save ASRagab/7cb4169449e575a0d6b1b299f0f0e1e6 to your computer and use it in GitHub Desktop.
bash: Run parallel commands and fail if any of them fails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /bin/bash | |
# | |
# Run parallel commands and fail if any of them fails. | |
# | |
set -eu | |
pids=() | |
for x in 1 2 3; do | |
ls /not-a-file & | |
pids+=($!) | |
done | |
for pid in "${pids[@]}"; do | |
wait "$pid" | |
done |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /bin/bash | |
# | |
# Run parallel commands and fail if any of them fails. | |
# | |
# The expected output is something like this: | |
# | |
# $ ./parallel-explained | |
# ls: cannot access '/not-a-file': No such file or directory | |
# ls: cannot access '/not-a-file'ls: cannot access '/not-a-file': No such file or directory | |
# : No such file or directory | |
# | |
# Our 'parallel-explained' script exited with code '2', because it's the exit | |
# code of one of the failed 'ls' jobs: | |
# | |
# $ echo $? | |
# 2 | |
# | |
# 'set -e' tells the shell to exit if any of the foreground command fails, | |
# i.e. exits with a non-zero status. | |
set -eu | |
# Initialize array of PIDs for the background jobs that we're about to launch. | |
pids=() | |
for x in 1 2 3; do | |
# Run a command in the background. We expect this command to fail. | |
ls /not-a-file & | |
# Add the PID of this background job to the array. | |
pids+=($!) | |
done | |
# Wait for each specific process to terminate. | |
# Instead of this loop, a single call to 'wait' would wait for all the jobs | |
# to terminate, but it would not give us their exit status. | |
# | |
for pid in "${pids[@]}"; do | |
# | |
# Waiting on a specific PID makes the wait command return with the exit | |
# status of that process. Because of the 'set -e' setting, any exit status | |
# other than zero causes the current shell to terminate with that exit | |
# status as well. | |
# | |
wait "$pid" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment