How to check in a bash script if something is running and exit if it is

后端 未结 9 1920
悲&欢浪女
悲&欢浪女 2021-02-06 00:24

I have a script that runs every 15 minutes but sometimes if the box is busy it hangs and the next process will start before the first one is finished creating a snowball effect.

相关标签:
9条回答
  • 2021-02-06 00:59

    Why don't set a lock file ?

    Something like

    yourapp.lock

    Just remove it when you process is finished, and check for it before to launch it.

    It could be done using

    if [ -f yourapp.lock ]; then
    echo "The process is already launched, please wait..."
    fi
    
    0 讨论(0)
  • 2021-02-06 01:05

    In lieu of pidfiles, as long as your script has a uniquely identifiable name you can do something like this:

    #!/bin/bash
    COMMAND=$0
    # exit if I am already running
    RUNNING=`ps --no-headers -C${COMMAND} | wc -l`
    if [ ${RUNNING} -gt 1 ]; then
      echo "Previous ${COMMAND} is still running."
      exit 1
    fi
    ... rest of script ...
    
    0 讨论(0)
  • 2021-02-06 01:05

    Use this script:

    FILE="/tmp/my_file"
    if [ -f "$FILE" ]; then
       echo "Still running"
       exit
    fi
    trap EXIT "rm -f $FILE"
    touch $FILE
    
    ...script here...
    

    This script will create a file and remove it on exit.

    0 讨论(0)
提交回复
热议问题