brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: wait PID gives you the exit code of one bash background job

Bash
~/tips/tip-bash-wait-pid-exit-code

wait "$db_pid"; db_status=$?

Run jobs in parallel and still check which of them failed.

Starting jobs with & makes a script faster, but a plain wait at the end throws away whether they worked. Waiting for each PID gives you the status back.

Save $! right after starting each job, and wait for the PIDs one by one:

backup_db &      db_pid=$!
backup_files &   files_pid=$!

wait "$db_pid";    db_status=$?
wait "$files_pid"; files_status=$?

echo "db: $db_status, files: $files_status"
(( db_status == 0 && files_status == 0 )) || exit 1

wait PID blocks until that job ends and returns its exit code. The order of waiting does not matter: if a job already finished, wait returns at once with the stored status.

For many jobs, keep the PIDs in an array and loop over it, counting the failures.

I prefer this to wait without arguments, which always returns 0 after all jobs end, whatever happened to them. Two details: wait only works for children of this shell, so a PID from somewhere else gives an error. And under set -e a failing wait stops the script before you read $?, so write wait "$pid" || status=$? there.

Further reading: Bash manual: Job Control Builtins (wait)

More Bash tips echo {01..10} cmd > file 2>&1 export HISTIGNORE='ls*:pwd:cd*' #rsync -av --delete /srv/media/ /mnt/backup/media/ APP_HOST=example.com All Bash tips (52) All topics

Link