Introduction
Sometimes scripts start tasks that run in the background. You want to pause the script until those tasks finish to keep things in order.
wait [job_id or process_id]sleep 5 &
waitsleep 10 &
pid=$!
wait $pid#!/bin/bash echo "Starting background task..." sleep 3 & wait echo "Background task finished!"
wait command do in a bash script when used without any arguments?wait without argumentswait command without arguments pauses the script until all background jobs started by the script finish.pid?wait $pid, where $pid is the process ID variable.-p or --pid are invalid in bash. Also, wait pid without $ won't expand the variable.sleep 3 & pid1=$! sleep 5 & pid2=$! wait $pid1 echo "First done" wait $pid2 echo "Second done"
wait $pid1 waits for the 3-second sleep to finish first.sleep 4 & wait pid echo "Done"
pid is not defined.wait pid without a $ sign, so bash treats 'pid' as a literal string, not a variable.wait $pid1 $pid2 $pid3 waits for all three specific processes to finish.cmd1 & cmd2 & cmd3 & wait $!) waits only for last background job. cmd1 & cmd2 & cmd3 & wait (cmd1 & cmd2 & cmd3 & wait) waits for all background jobs but does not track PIDs explicitly. cmd1 & pid1=$!; cmd2 & pid2=$!; cmd3 & pid3=$!; wait saves PIDs but then uses wait without arguments, so the PID variables are unused and it waits for all jobs.Pass the test and this pattern moves unknown