我有一个执行备份的 shell 脚本。我在 cron 中设置了这个脚本,但问题是备份很重,因此可以在第一个 rsync 结束之前执行第二个 rsync。 我想在脚本中启动 rsync,然后获取 PID 并编写一个文件,该脚本检查进程是否存在(如果该文件存在或不存在)。 如果我将 rsync 放在后台,我会得到 PID,但我不知道如何知道 rsync 何时结束,但是,如果我设置 rsync (无后台),我无法在进程完成之前获取 PID,因此我无法编写带 PID 的文件。
我不知道“拥有 rsync 控制”并知道它何时完成的最佳方法是什么。
我的脚本
#!/bin/bash
pidfile="/home/${USER}/.rsync_repository"
if [ -f $pidfile ];
then
echo "PID file exists " $(date +"%Y-%m-%d %H:%M:%S")
else
rsync -zrt --delete-before /repository/ /mnt/backup/repositorio/ < /dev/null &
echo $$ > $pidfile
# If I uncomment this 'rm' and rsync is running in background, the file is deleted so I can't "control" when rsync finish
# rm $pidfile
fi
有人可以帮我吗?
提前致谢!! :)
最佳答案
# check to make sure script isn't still running
# if it's still running then exit this script
sScriptName="$(basename $0)"
if [ $(pidof -x ${sScriptName}| wc -w) -gt 2 ]; then
exit
fi
- pidof 查找进程的 pid
- -x 告诉它也查找脚本
- ${sScriptName} 只是脚本的名称...您可以对此进行硬编码
- wc -w 按字数返回字数
- -gt 2 运行的实例不超过一个(实例加 1 用于 pidof 检查)
- 如果有多个实例正在运行,则退出脚本
请告诉我这是否适合您。
关于linux - 来自 shell 脚本的后台 rsync 和 pid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37749151/