Skip to content

Instantly share code, notes, and snippets.

@darccio
Last active August 23, 2017 22:15
Show Gist options
  • Save darccio/ca06ed671ca56b548cae71b348417739 to your computer and use it in GitHub Desktop.
Save darccio/ca06ed671ca56b548cae71b348417739 to your computer and use it in GitHub Desktop.
PID Shield: protect your commands against parallel execution
#!/bin/bash
##
## PID Shield: protect your commands against parallel execution
##
## Author: Dario Castañé <i@dario.im>
##
## License: Public domain; do as you wish
##
pidshield() {
hash=$(echo -n "$@" | md5sum | cut -f1 -d' ')
filename="/tmp/psh-$hash-$(id -un).pid"
unset hash
if [ -f "$filename" ]; then
# Stale PID file check
running=$(pgrep -c --pidfile "$filename")
[ "$running" -eq 0 ] && rm -f "$filename" || exit 0
unset running
fi
trap 'rm -f '"$filename" EXIT
echo $$ >"$filename"
unset filename
"$@"
bash -c "$(trap -p | grep -E "EXIT$" | sed "s/trap -- '//;s/' EXIT$//")"
trap - EXIT
}
## Usage: pidshield your_command --as usual
## Don't use it in your interactive shell, only in scripts.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment