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

后端 未结 13 946
無奈伤痛
無奈伤痛 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条回答
  •  猫巷女王i
    2020-12-31 06:25

    Never use a lock file always use a lock directory. In your specific case, it's not so important because the start of the script is scheduled in 5min intervals. But if you ever reuse this code for a webserver cgi-script you are toast.

    if mkdir /tmp/my_lock_dir 2>/dev/null
    then
       echo "running now the script"
       sleep 10
       rmdir /tmp/my_lock_dir
    fi
    

    This has a problem if you have a stale lock, means the lock is there but no associated process. Your cron will never run.

    Why use a directory? Because mkdir is an atomic operation. Only one process at a time can create a directory, all other processes get an error. This even works across shared filesystems and probably even between different OS types.

提交回复
热议问题