Skip to content

Instantly share code, notes, and snippets.

@manovotny
Last active November 12, 2024 10:33
Show Gist options
  • Select an option

  • Save manovotny/5352248d3553da4d77dc to your computer and use it in GitHub Desktop.

Select an option

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
@se-bre
Copy link

se-bre commented Nov 12, 2024

just found this - pgrep does the job (just be careful with cron and using different shells in script and cron ;)

function check_script_running () {
        for pid in $(pgrep -f $(basename $0))
        do
            if [ $pid != $$ ] 
            then
                echo "[$(date)] : $(basename $0) : Process is already running with PID $pid"
                exit 1
            else
              echo "Running with PID $pid"
            fi
        done
}

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