Do not let run same script at the same time

I have sheduled my detection collection to run every hour. The collection are getting larger and already have developed some child script which will run 3 hours or something. Today i have learned this brilliant command flock which will make sure if your executed script is not running already. So the script will be not executed if it still are doing his job.

For example this is my line in crontab now:
10 * * * * flock -n ~/check.pid -c ~/detect/check-all.sh
You can still broke the process by manual executing:
~/detect/check-all.sh
But cronjob will not break your system :)

Integrate flock in the main script inside:
#!/bin/bash

exec {lock_fd}>~/$(basename $0).pid || exit 1
flock -n "$lock_fd" || { echo "ERROR: flock() failed." >&2; exit 1; }

# ... commands executed under lock ...
echo "$(basename $0)"
sleep 10

flock -u "$lock_fd"
Without output:
#!/bin/bash

exec {lock_fd}>~/$(basename $0).pid || exit 1
flock -n "$lock_fd" || exit 1

# ... commands executed under lock ...
echo "$(basename $0) started at $(date +%Y%m%d%H%M)"
sleep 10

flock -u "$lock_fd"

No comments: