← Back to all snippets
BASH

Executing Multiple Commands in Parallel for Speedup

Accelerate Bash scripts by running multiple independent commands concurrently using job control, ideal for speeding up build processes or fetching data in web development.

#!/bin/bash\n\necho "Starting parallel tasks..."\n\n# Task 1: Simulate a long-running process (e.g., building frontend assets)\n( echo "Task 1: Building Frontend Assets..." ; sleep 3 ; echo "Task 1: Frontend Assets Built." ) &\nPID1=$! # Store the Process ID of the background job\n\n# Task 2: Simulate another long-running process (e.g., compiling backend code)\n( echo "Task 2: Compiling Backend Code..." ; sleep 4 ; echo "Task 2: Backend Code Compiled." ) &\nPID2=$! # Store the Process ID of the background job\n\n# Task 3: Simulate fetching a remote resource (e.g., downloading dependencies)\n( echo "Task 3: Downloading Dependencies..." ; sleep 2 ; echo "Task 3: Dependencies Downloaded." ) &\nPID3=$! # Store the Process ID of the background job\n\necho "All background tasks initiated. Waiting for them to complete..."\n\n# Wait for each specific background job to complete\n# This ensures that the script only proceeds when ALL tasks are done\nwait $PID1\necho "Confirmed PID $PID1 (Task 1) finished."\nwait $PID2\necho "Confirmed PID $PID2 (Task 2) finished."\nwait $PID3\necho "Confirmed PID $PID3 (Task 3) finished."\n\necho "All parallel tasks completed successfully."\n\n# You can also use 'wait' without arguments to wait for all background jobs\n# wait # (Uncomment this line and remove individual waits above if you prefer)\n# echo "All background jobs finished using 'wait' without arguments."
How it works: This Bash snippet demonstrates how to run multiple commands concurrently, significantly speeding up script execution by leveraging job control. Each command or sequence of commands enclosed in parentheses `()` and followed by an ampersand `&` is run in a subshell as a background process. The script captures the Process ID (PID) of each background job using `$!`. Finally, `wait $PID` is used to pause the script's execution until a specific background job completes, ensuring all parallel tasks finish before the script proceeds. This is extremely useful for web developers to parallelize build steps, tests, or data fetching in CI/CD pipelines.

Need help integrating this into your project?

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

Hire DigitalCodeLabs