Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
inotifywait的Bash脚本-如何将删除写入日志文件,以及cp close_写入?_Bash_Inotify - Fatal编程技术网

inotifywait的Bash脚本-如何将删除写入日志文件,以及cp close_写入?

inotifywait的Bash脚本-如何将删除写入日志文件,以及cp close_写入?,bash,inotify,Bash,Inotify,我有一个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/b

我有一个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\u WRITE,CLOSE
。这就是我现在签入代码的原因。 我还尝试检查了
删除
,但由于某种原因,代码部分不起作用。请查看:

#!/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

在目录中,我触摸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

您如何执行此操作。是否将此脚本进程发送到后台?@Codex73您可以像执行任何其他脚本一样执行它,如果希望它像任何其他脚本一样在后台运行,则可以将其发送到后台。