Skip to content

Instantly share code, notes, and snippets.

@darth-veitcher
Created January 8, 2017 22:13
Show Gist options
  • Select an option

  • Save darth-veitcher/f47eb0a52ae42a1c5e9a65adca460723 to your computer and use it in GitHub Desktop.

Select an option

Save darth-veitcher/f47eb0a52ae42a1c5e9a65adca460723 to your computer and use it in GitHub Desktop.

Revisions

  1. darth-veitcher created this gist Jan 8, 2017.
    42 changes: 42 additions & 0 deletions bash-pid.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    Pattern below allows for a bash script to be called via, say, cron and check to see if it is already running.

    Useful for things like `rsync` tasks.

    ```bash
    PIDFILE=/var/run/myscriptname.pid

    if [ -f $PIDFILE ]
    then
    PID=$(cat $PIDFILE)
    ps -p $PID > /dev/null 2>&1
    if [ $? -eq 0 ]
    then
    echo "Process already running"
    exit 1
    else
    ## Process not found assume not running
    echo $$ > $PIDFILE
    if [ $? -ne 0 ]
    then
    echo "Could not create PID file"
    exit 1
    fi
    fi
    else
    echo $$ > $PIDFILE
    if [ $? -ne 0 ]
    then
    echo "Could not create PID file"
    exit 1
    fi
    fi


    # Main script ... Do work here

    ...

    # End

    rm $PIDFILE
    ```