BASH
Execute Multiple Commands Concurrently
Improve development efficiency by running multiple long-running tasks or scripts in parallel using bash backgrounding and the `wait` command.
#!/bin/bash
# Usage: ./run_concurrently.sh
echo "Starting concurrent tasks..."
# Task 1: A simple delay
(
echo "Task 1: Starting (sleep 5s)"
sleep 5
echo "Task 1: Finished"
) &
TASK1_PID=$!
# Task 2: Another simple delay
(
echo "Task 2: Starting (sleep 3s)"
sleep 3
echo "Task 2: Finished"
) &
TASK2_PID=$!
# Task 3: Simulating a dev server or watcher
(
echo "Task 3: Starting (long-running sim)"
# Replace with actual command like 'npm run dev' or 'webpack --watch'
# For demonstration, a long sleep or endless loop
sleep 7
echo "Task 3: Finished"
) &
TASK3_PID=$!
echo "All tasks started. Waiting for them to complete..."
# Wait for all backgrounded jobs to finish
wait "$TASK1_PID" "$TASK2_PID" "$TASK3_PID"
echo "All concurrent tasks completed."
# You can also check exit codes if needed
# wait -n # waits for next job, then check $?
# For simplicity, we just wait for all.
How it works: This script demonstrates how to run multiple commands or functions in parallel using bash. Each command enclosed in parentheses `()` and followed by an ampersand `&` is executed in a subshell as a background process. The script then stores their Process IDs (`$!`) and uses the `wait` command to pause execution until all specified background processes have completed. This technique is highly beneficial for optimizing build processes, running multiple watchers (e.g., CSS, JavaScript, backend server) during development, or orchestrating parallel deployments.