Skip to content

Instantly share code, notes, and snippets.

@manovotny
Last active September 22, 2023 07:15
Show Gist options
  • Save manovotny/5352248d3553da4d77dc to your computer and use it in GitHub Desktop.
Save manovotny/5352248d3553da4d77dc to your computer and use it in GitHub Desktop.
Bash script to check if a script is already running.
#!/bin/bash
dupe_script=$(ps -ef | grep "SCRIPT_NAME.sh" | grep -v grep | wc -l | xargs)
if [ ${dupe_script} -gt 2 ]; then
echo -e "The SCRIPT_NAME.sh script was already running!"
exit 0
fi
@cemysf
Copy link

cemysf commented Aug 1, 2023

How about determining the script name like this?

#!/bin/bash

SCRIPT_NAME=$(basename "$0")
dupe_script=$(ps -ef | grep "$SCRIPT_NAME" | grep -v grep | wc -l | xargs)

if [ ${dupe_script} -gt 2 ]; then
    echo -e "The $SCRIPT_NAME script was already running!"
    exit 0
fi

@gmillerd
Copy link

gmillerd commented Sep 22, 2023

consider looking at "pgrep", one for "-c" to count the pids and two for -f "for full path", three -u for uid running, and execute with fqfn so that the script is "/path/to/script/runtime.sh" not "runtime.sh". Now you can run multiple scripts of the same name and not get conflicts between them (eg, ~/bin/cron.sh and ~/test/cron.sh) and other user's cron.sh won't clash, or when you are editing cron.sh (eg, "emacs cron.sh")

https://man7.org/linux/man-pages/man1/pgrep.1.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment