Bash wait

Today I learned about the ‘wait’ command. It waits for background processes to terminate before returning, so you can fire off a bunch of jobs to be run in parallel and then wait for all of them to complete before continuing, like in this take-ownership.sh script I wrote tonight:

#!/bin/bash
if [ -n "$1" ]; then
  pushd "$1" > /dev/null 2>&1
  if [ "$?" -ne "0" ]; then
    echo "Cannot change dir to '$1'.";
    exit 1;
  fi
fi
sudo chown -R jj5:jj5 . &
sudo find . -type d -exec chmod u+rwx {} \; &
sudo find . -type f -exec chmod u+rw {} \; &
if [ -n "$1" ]; then
  popd > /dev/null 2>&1
fi
wait
exit 0