BASH

Run Commands in Parallel and Wait

Optimize Bash script execution by running multiple independent commands concurrently in the background using `&`, then wait for all of them to complete using the `wait` command.

#!/bin/bash

echo "--- Starting parallel tasks ---"
START_TIME=$(date +%s)

# Function to simulate a long-running task
simulate_task() {
  local task_name="$1"
  local duration="$2"
  echo "Task '$task_name' started. Will run for ${duration} seconds."
  sleep "$duration"
  echo "Task '$task_name' finished after ${duration} seconds."
}

# Run tasks in the background
simulate_task "Task A" 3 & # Runs in background
PID_A=$! # Get the PID of the last background command

simulate_task "Task B" 5 & # Runs in background
PID_B=$!

simulate_task "Task C" 2 & # Runs in background
PID_C=$!

echo "All tasks launched in background. PIDs: $PID_A, $PID_B, $PID_C"

# Wait for all background jobs to complete
# 'wait' without arguments waits for all background jobs of the current shell
echo "Waiting for all tasks to complete..."
wait
echo "All background tasks completed."

# You can also wait for specific PIDs
# echo "Waiting specifically for Task B..."
# wait "$PID_B"
# echo "Task B finished."

END_TIME=$(date +%s)
RUNTIME=$((END_TIME - START_TIME))
echo "--- All parallel tasks finished in ${RUNTIME} seconds ---"

echo "--- Demonstration of a sequential task after parallel ---"
echo "This command runs only after all parallel tasks are done."
echo "Sequential task completed."
How it works: This snippet demonstrates how to run multiple commands or functions concurrently in a Bash script. Appending `&` to a command sends it to the background, allowing the script to continue execution immediately. The `wait` command, when used without arguments, pauses the script's execution until all child processes launched in the background from the current shell have completed. This significantly speeds up scripts by performing independent operations in parallel rather than sequentially.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs