用于 inotifywait 的 Bash 脚本 - 如何将删除写入日志文件和 cp close_writes



我有这个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.棒!

您需要将

-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

相关内容

  • 没有找到相关文章

最新更新