0

Is this a valid way of check that no two executions of a script run at the same time? Or is it a race condition?

#!/bin/bash
if test "$(pgrep -f 'something-unique-about-this-script' | wc -l)" -ne 1
then
    echo "Too many instances"
    exit 1
fi
jleeothon
  • 2,907
  • 4
  • 19
  • 35
  • Does this answer your question? [What is the best way to ensure only one instance of a Bash script is running?](https://stackoverflow.com/questions/1715137/what-is-the-best-way-to-ensure-only-one-instance-of-a-bash-script-is-running) – Michael Jaros May 18 '20 at 10:51
  • I don't think this is a duplicate as this question is not *"**how** to ensure that ..."* but explicitly about the dangers of pgrep. – Socowi May 18 '20 at 11:31

1 Answers1

0

mkdir is an atomic command, so I like

if ! mkdir ~/.app_lock_dir; then
    echo already running >&2
    exit 1
fi
# schedule the dir for removal
trap 'rm ~/.app_lock_dir' EXIT
glenn jackman
  • 238,783
  • 38
  • 220
  • 352