Two sleep commands run in background: one sleeps 3 seconds, the other 5 seconds. wait $pid1 waits for the 3-second sleep to finish first.
Step 2: Trace the echo outputs
After the first wait, it prints "First done". Then it waits for the 5-second sleep and prints "Second done".
Final Answer:
First done
Second done -> Option A
Quick Check:
Waits print in order of completion [OK]
Hint: Wait commands print in order of waited process completion [OK]
Common Mistakes:
Assuming both echo print immediately
Confusing order of wait calls
Ignoring background process durations
4. What is wrong with this script snippet?
sleep 4 &
wait pid
echo "Done"
Assuming pid is not defined.
medium
A. The script will wait for all background jobs anyway.
B. The script will wait for a process named 'pid'.
C. The script will throw an error because pid is undefined.
D. The script will ignore the wait command.
Solution
Step 1: Check variable usage in wait command
The script uses wait pid without a $ sign, so bash treats 'pid' as a literal string, not a variable.
Step 2: Understand effect of undefined variable
Since 'pid' is not a valid PID and not defined, wait will fail with an error about invalid PID or job.
Final Answer:
The script will throw an error because pid is undefined. -> Option C
Quick Check:
Use $pid to expand variable; missing $ causes error [OK]
Hint: Always use $ before variable names in wait [OK]
Common Mistakes:
Forgetting $ before variable
Assuming wait accepts names
Ignoring error messages
5. You want to run three commands in background, capture their PIDs, and then wait specifically for those three processes to finish before continuing. Which script snippet correctly does this?
Each command runs in background and its PID is saved in separate variables.
Step 2: Use wait with all PIDs
Using wait $pid1 $pid2 $pid3 waits for all three specific processes to finish.
Step 3: Analyze other options
cmd1 & cmd2 & cmd3 & wait $! (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.