Shell 脚本:如果脚本已经运行,请确保不执行该脚本 [英] Shell script: Ensure that script isn't executed if already running

查看:30
本文介绍了Shell 脚本:如果脚本已经运行,请确保不执行该脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
确保一次只运行一个 shell 脚本实例的快速而肮脏的方法

我已经设置了一个 cronjob 来正确备份我的文件夹,我为此感到非常自豪.但是,通过查看备份结果,我发现我的备份脚本已被 Crontab 多次调用,导致同时运行多个备份.

I've set up a cronjob to backup my folders properly which I am quite proud of. However I've found out, by looking at the results from the backups, that my backup script has been called more than once by Crontab, resulting in multiple backups running at the same time.

如果同一个脚本已经在执行,有什么办法可以确保某个 shell 脚本不会运行?

Is there any way I can ensure that a certain shell script to not run if the very same script already is executing?

推荐答案

一个没有竞争条件或提前退出问题的解决方案是使用锁文件.flock 实用程序可以很好地处理这个问题,可以像这样使用:

A solution without race condition or early exit problems is to use a lock file. The flock utility handles this very well and can be used like this:

flock -n /var/run/your.lockfile -c /your/script

如果脚本已经在运行,它将立即以非 0 状态返回.

It will return immediately with a non 0 status if the script is already running.

这篇关于Shell 脚本:如果脚本已经运行,请确保不执行该脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆