Skip to content

Instantly share code, notes, and snippets.

@coderofsalvation
Last active January 2, 2016 05:39
Show Gist options
  • Save coderofsalvation/8258606 to your computer and use it in GitHub Desktop.
Save coderofsalvation/8258606 to your computer and use it in GitHub Desktop.
limit shellscript process to only one 1 process, to prevent running twice
# forces/limits shellscript to only one 1 process, to prevent running twice, aka bash singleton
# this function exits when no parameter is passed, and another instance of the script is detected
# @dependancies ps grep tr sed
# @param string (pass --kill to kill previous process)
# usage: change 'foo' and 'bar' to the strings which occur in your process name
function singleprocess(){
PID=$$; # current process
if [[ "$1" == "--kill" ]]; then
PID="$(ps aux | grep foo | grep bar | tr -s [:space:] | cut -d' ' -f2 )"
[[ $? == 0 ]] && [[ ${#PID} != 0 ]] && echo "killing previous pid $PID" && kill -9 $PID
else
ps aux | grep "$(basename $0)" | grep -v grep | grep -v $PID &>/dev/null && exit 0; # dont run twice
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment