Introduction
Running tasks at the same time saves time and makes your scripts faster.
command1 & command2 & wait
sleep 3 & sleep 5 & wait echo "All done"
curl http://example.com/file1 & curl http://example.com/file2 & wait
for i in {1..3}; do echo "Task $i started" sleep $((RANDOM % 3 + 1)) & done wait echo "All tasks finished"
#!/bin/bash echo "Starting tasks..." sleep 2 & sleep 4 & sleep 3 & wait echo "All tasks completed!"
& at the end of a command in a bash script do?& in bash& symbol placed at the end of a command tells bash to run that command in the background.& to a command runs it in the background. To run two commands in parallel, both must have &.command1 & command2 & runs both commands with &, so both run in background simultaneously. command1 && command2 & uses && which means run second only if first succeeds, then runs second in background (but first runs in foreground). command1 && command2 uses && without background. command1 & command2 runs command1 in background but command2 in foreground, so the script blocks until command2 finishes.command1 & command2 & -> Option Aecho "Start" sleep 2 & echo "Middle" sleep 1 & echo "End" wait
sleep commands run in background due to &, so they do not block the script. The echo commands run immediately in order.wait pauses script exit until sleeps finish but does not affect output order.command1 & command2 wait
command1 has & to run in background. command2 runs in foreground, blocking until it finishes.wait command waits for all background jobs to finish. Since only command1 is background, wait waits only for it. command2 runs before wait.script1.sh, script2.sh, and script3.sh in parallel and then print "All done" only after all finish. Which is the best way to do this?& after each script runs them in parallel without waiting.wait command pauses the script until all background jobs complete, ensuring synchronization.wait, echo "All done" runs, confirming all scripts finished../script1.sh & ./script2.sh & ./script3.sh & wait echo "All done"-> Option B
Pass the test and this pattern moves unknown