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

  1. Function eai: This function executes a command, announces it, and interrupts the process if the command fails.
  2. Array commands: This array holds the commands you want to execute in parallel. Replace the sleep commands with your actual commands.
  3. Execute Commands in Parallel: The loop iterates over each command and runs it in the background using the & operator.
  4. 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.