How do I make sure my bash script isn't already running?

后端 未结 13 834
無奈伤痛
無奈伤痛 2020-12-31 05:56

I have a bash script I want to run every 5 minutes from cron... but there\'s a chance the previous run of the script isn\'t done yet... in this case, i want the new run to j

13条回答
  •  时光说笑
    2020-12-31 06:18

    As a one-liner and if you do not want to use a lockfile (e.g. b/c/ of a read only filesystem, etc)

    test "$(pidof -x $(basename $0))" != $$ && exit
    

    It checks that the full list of PID that bear the name of your script is equal to the current PID. The "-x" also checks for the name of shell scripts.

    Bash makes it even shorter and faster:

    [[ "$(pidof -x $(basename $0))" != $$ ]] && exit
    

提交回复
热议问题