Skip to content

Instantly share code, notes, and snippets.

@opensiriusfox
Last active June 2, 2018 22:31
Show Gist options
  • Save opensiriusfox/48303c34b3265c3e39236717fc082e1f to your computer and use it in GitHub Desktop.
Save opensiriusfox/48303c34b3265c3e39236717fc082e1f to your computer and use it in GitHub Desktop.
waitdone - A simple bash script to sleep until another proccess is done.
#!/bin/bash
# waitdone
###############################################################################
# A simple bash script to sleep until another process is done. This is handy
# if you have an executable running in another tab/session/etc and want to
# automatically run a dependent command when the first finishes, or if you
# want to queue up another command that will make use of the same system
# resources being locked by the currently executing process.
###############################################################################
# VERSION HISTORY
# 2018-06-02 1.0 First Public Release
###############################################################################
#set -u
# Parse arguments for how many times to confirm a process has stopped,
# and how long to wait between checks.
#########
if [[ $# -lt 1 || $# -gt 3 ]]; then
echo "Usage: $0 <proc_name> [repeat count] [recheck_time=5]"
exit
fi
if [[ $# -gt 1 ]]; then
repeatCount=$(("$2"+1))
else
repeatCount=1
fi
if [[ $# -gt 2 ]]; then
recheckSleepTime=$(("$3"+0))
if [[ $recheckSleepTime -lt 1 ]]; then
recheckSleepTime=1
fi
else
recheckSleepTime=5
fi
OIFS="$IFS"
IFS=$'\n'
function printLonely() {
printf "\r%-${COLUMNS}s" "$1"
}
# Start the process search counter
#########
startTime=$(date +"%s")
while [[ $repeatCount -gt 0 ]]; do
# get a list of running processes
processes=($(ps a))
found=false
# for each entry line, see if it matches our search term
# rejecting all calls to this tool that will also show up in the list.
for process in ${processes[*]}; do
echo "$process" | grep -v "$0" | grep "$1" >/dev/null
RETCODE=$?
if [[ $RETCODE -eq 0 ]]; then
found=true
break
fi
done
if [[ $found == false ]]; then
repeatCount=$(($repeatCount-1))
fi
if [[ $repeatCount -eq 0 ]]; then
printf "\tdone!\n"
exit
else
# If we haven't found it, then update a timestamp to show the user how
# long we have been waiting, and sleep until the next check.
timeDelta=$(($(date +"%s")-$startTime))
sleepTime="$(date --date=@$timeDelta -u +"%H:%M:%S")"
printLonely "sleep... ($sleepTime)"
sleep $recheckSleepTime
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment