我有这个bash脚本:
#!/bin/bash
inotifywait -m -e close_write --exclude '\*.sw??$' . |
#adding --format %f does not work for some reason
while read dir ev file; do
cp ./"$file" zinot/"$file"
done
~
现在,我如何让它执行相同的操作,还可以通过将文件名写入日志文件来处理删除操作? 有点像?
#!/bin/bash
inotifywait -m -e close_write --exclude '\*.sw??$' . |
#adding --format %f does not work for some reason
while read dir ev file; do
# if DELETE, append $file to /inotify.log
# else
cp ./"$file" zinot/"$file"
done
~
编辑:
通过查看生成的消息,我发现只要文件关闭,inotifywait就会生成CLOSE_WRITE,CLOSE
。这就是我现在正在检查我的代码。
我还尝试检查DELETE
,但由于某种原因,该部分代码无效。看看:
#!/bin/bash
fromdir=/path/to/directory/
inotifywait -m -e close_write,delete --exclude '\*.sw??$' "$fromdir" |
while read dir ev file; do
if [ "$ev" == 'CLOSE_WRITE,CLOSE' ]
then
# copy entire file to /root/zinot/ - WORKS!
cp "$fromdir""$file" /root/zinot/"$file"
elif [ "$ev" == 'DELETE' ]
then
# trying this without echo does not work, but with echo it does!
echo "$file" >> /root/zinot.txt
else
# never saw this error message pop up, which makes sense.
echo Could not perform action on "$ev"
fi
done
在目录中,我做touch zzzhey.txt
。文件已复制。我执行vim zzzhey.txt
并复制文件更改。我执行rm zzzhey.txt
并将文件名添加到我的日志文件zinot.txt
中。真棒!
答案 0 :(得分:1)
您需要将-e delete
添加到您的监视器,否则DELETE
事件将不会传递给循环。然后为处理事件的循环添加一个条件。这样的事情应该做:
#!/bin/bash
inotifywait -m -e delete -e close_write --exclude '\*.sw??$' . |
while read dir ev file; do
if [ "$ev" = "DELETE" ]; then
echo "$file" >> /inotify.log
else
cp ./"$file" zinot/"$file"
fi
done