Parallel Execution in Shell
To execute multiple commands in parallel in a shell script and wait for all of them to finish, you can use background jobs and the wait
command. Here's an example script that demonstrates how to do this:
#!/bin/bash
# Function to execute and announce a command
eai() {
echo "Executing: $@"
"$@"
if [ $? -ne 0 ]; then
echo "Command failed: $@"
exit 1
fi
}
# Array of commands to run in parallel
commands=(
"sleep 3" # Replace these commands with your actual commands
"sleep 5"
"sleep 2"
)
# Execute each command in the background
for cmd in "${commands[@]}"; do
eai $cmd &
done
# Wait for all background jobs to finish
wait
echo "All commands have completed."
Explanation
- Function
eai
: This function executes a command, announces it, and interrupts the process if the command fails. - Array
commands
: This array holds the commands you want to execute in parallel. Replace thesleep
commands with your actual commands. - Execute Commands in Parallel: The loop iterates over each command and runs it in the background using the
&
operator. - Wait for Completion: The
wait
command waits for all background jobs to finish before proceeding.
This approach ensures that all commands are executed in parallel and the script waits for all of them to complete before moving on. If any command fails, the eai
function will handle the error and stop the script execution.