1

我有这个 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
~

编辑:

通过查看生成的消息,我发现CLOSE_WRITE,CLOSE每当文件关闭时都会生成 inotifywait。这就是我现在检查我的代码的内容。我也尝试检查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中。惊人的!

4

1 回答 1

2

您需要添加-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
于 2012-11-17T11:32:22.053 回答