Stop your scripts from hanging on stale file locks
Technical Briefing | 10/11/2026
You probably have a few scripts running via cron or systemd timers that do heavy lifting. Most of the time they finish in seconds, but then the network glitches, or a database query locks up, and suddenly your script is still running three hours later. If you aren’t handling locking, your next execution triggers, and you end up with a dozen processes fighting over the same files.
The trap of using touch to track state
A lot of people reach for touch to create a flag file and rm to remove it. I did this for years. It fails the moment the script hits an unhandled error or gets a SIGKILL. You end up with a leftover lock file, and your script refuses to run until you manually delete it. Don’t build your own lock management when the kernel has better ways to handle it.
flock -n /var/run/my_script.lock /usr/local/bin/do_the_thing.sh
- The -n flag tells flock to exit immediately if the lock is already held
- Using a file descriptor instead of a file path keeps the lock tied to the process lifetime
- The kernel cleans up the lock automatically when your process exits, crash or not
Going beyond the one-liner
If you need to wrap a larger block of logic, put the flock call inside the script itself rather than the crontab. Open a file descriptor, perform an exclusive lock on it, and everything inside that subshell will inherit the protection. It keeps your crontab clean and makes the locking logic portable across environments.
Next time you find yourself adding complex logic to check process IDs, stop and remember that flock has been in util-linux for ages. It handles the cleanup that you are currently doing with error-prone cleanup traps. Let the kernel handle the state management while you worry about the data.
