TASK_PID is the PID of a background command that exits with status 7.
Print that command's exit status after it finishes.
bash -c 'sleep 1; exit 7' &
TASK_PID=$!Which command is appropriate?
wait blocks until the specified process ends and returns its exit status to the current shell.
Detailed explanation
jobs -l; printf '%s\n' "$?"Incorrect. jobs lists jobs but does not wait for the target PID or return its status.
Incorrect. jobs lists jobs but does not wait for the target PID or return its status.
sleep 1; printf '%s\n' "$?"Incorrect. It prints sleep's status, not the background command's status.
Incorrect. It prints sleep's status, not the background command's status.
kill -0 "$TASK_PID"; printf '%s\n' "$?"Incorrect. kill -0 checks whether a signal could be sent; it does not retrieve an exit status.
Incorrect. kill -0 checks whether a signal could be sent; it does not retrieve an exit status.
wait "$TASK_PID"; printf '%s\n' "$?"Correct. wait returns the target process's exit status in the current shell.
Correct. wait returns the target process's exit status in the current shell.
Try it yourself
An example you can run in a temporary verification environment.
bash -c 'sleep 1; exit 7' &
TASK_PID=$!
wait "$TASK_PID"
TASK_STATUS=$?
printf 'status=%s
' "$TASK_STATUS"Expected result
status=7Key points
- Waiting for a PID
- The meaning of $? after wait
- Observation versus synchronization
Notes
- Environment: Bash 5.2
- Command output formatting can vary slightly by distribution or tool version.
- Run the example in a temporary directory or process when possible.
Foundation review
Read the scope first
Check whether the command acts on the current shell, a new process, an existing process, or a file.
Verify the observable result
Use the supplied command and compare the output with the expected result.