今天从大佬的博客里嫖到一个很赞的脚本,先附上大佬博客:https://www.cnblogs.com/f-ck-need-u/p/7220193.html
#!/bin/bash
watch_dir=/source
push_to=192.168.1.200
# First to do is initial sync
rsync -az --delete --exclude="*.swp" --exclude="*.swx" $watch_dir $push_to:/
inotifywait -mrq -e delete,close_write,moved_to,moved_from,isdir --timefmt '%Y-%m-%d %H:%M:%S' --format '%w%f:%e:%T' $watch_dir \
--exclude=".*.swp" >>/var/log/inotifywait.log &
while true;do
if [ -s "/var/log/inotifywait.log" ];then
grep -i -E "delete|moved_from" /var/log/inotifywait.log >> /var/log/inotify_away.log
rsync -az --delete --exclude="*.swp" --exclude="*.swx" $watch_dir/ $push_to:/
if [ $? -ne 0 ];then
echo "$watch_dir sync to $push_to failed at `date +"%F %T"`,please check it by manual" |\
mail -s "inotify+Rsync error has occurred" root@localhost
fi
cat /dev/null > /var/log/inotifywait.log
rsync -az --delete --exclude="*.swp" --exclude="*.swx" $watch_dir/ $push_to:/
else
sleep 1
fi
done
当把这个脚本用hup &挂后台时遇到了过去的残念问题——退出终端脚本后台会直接被杀掉,原因很简单。
如图,是SSH的子进程ssh-bash-inotify.sh
如果exit退出终端,就变成了这样
可见关闭终端会导致inotify.sh的父进程bash连同再上一级sshd都会被杀掉
(nohup /source/inotify.sh &)
所以用(nohup /source/inotify.sh &) 来启动就好了,() 小括号表示子shell,会直接成为主进程systemd的子进程,这样就脱离了sshd进程的控制,就可以挂后台啦