我有一个tar
每月运行一次的备份脚本。它从晚上一直运行到cron
。我还有一个电源计划,每天晚上 4.15 重新启动服务器。
tar
问题是脚本运行时服务器重新启动。
我可以在 bash 脚本的开头和结尾添加一些内容以在脚本处于活动状态时禁用重启吗?
答案1
这里是 Bash 常见问题解答中关于如何实现互斥锁的讨论:
http://mywiki.wooledge.org/BashFAQ/045
您可以实现类似的功能,但要让您的重启脚本循环直到锁释放。我还没有测试过以下内容,但这是一个起点:
Tar 脚本:
#!/bin/bash
lockdir=/tmp/myscript.lock
if mkdir "$lockdir"
then # directory did not exist, but was created successfully
echo >&2 "successfully acquired lock: $lockdir"
trap 'rm -rf "$lockdir"' 0 # remove directory when script finishes
# continue script
else
echo >&2 "cannot acquire lock, giving up on $lockdir"
exit 0
fi
# DO YOUR ORIGINAL TAR SCRIPT HERE
重启脚本:
#!/bin/bash
lockdir=/tmp/myscript.lock
while true; do
if mkdir "$lockdir"
then # directory did not exist, but was created successfully
trap 'rm -rf "$lockdir"' 0 # remove directory when script finishes
break # continue with script
else
sleep 5 # sleep for 5 seconds and try again
fi
done
# RUN YOUR REBOOT COMMANDS HERE
答案2
我将对该脚本的 PID 使用轮询技术。基本思路是等到脚本释放 PID(即退出),然后才转到重启脚本的下一步。当然,如果没有进程正在运行,脚本将继续重启。
#!/bin/bash
while pgrep -f my_backup_script_name.sh > /dev/null
do
sleep 0.25 # small delay so that the loop doesn't hog the CPU
done
shutdown -r now