inotifywait 建立监视后执行命令

lp1*_*051 6 shell bash shell-script inotify

在 shell 脚本 ( test.sh) 中,我有 inotifywait 递归监视一些目录 - “somedir”:

#!/bin/sh
inotifywait -r -m -e close_write "somedir" | while read f; do echo "$f hi"; done
Run Code Online (Sandbox Code Playgroud)

当我在终端中执行此操作时,我将收到以下消息:

Setting up watches.  Beware: since -r was given, this may take a while!
Watches established.
Run Code Online (Sandbox Code Playgroud)

我需要的是在建立手表触摸“somedir”下的所有文件。为此,我使用:

find "somedir" -type f -exec touch {}
Run Code Online (Sandbox Code Playgroud)

原因是当崩溃后启动inotifywait时,在此期间到达的所有文件将永远不会被拾取。所以问题和问题是,我应该如何或何时执行find + touch

到目前为止,我试图让它在我调用后几秒钟休眠test.sh,但是当“somedir”中的子目录数量会增加时,从长远来看这不起作用。

我试图检查该进程是否正在运行并休眠直到它出现,但似乎该进程在所有手表建立之前就出现了。

我试图改变test.sh

#!/bin/sh
inotifywait -r -m -e close_write "somedir" && find "somedir" -type f -exec touch {} | 
while read f; do echo "$f hi"; done
Run Code Online (Sandbox Code Playgroud)

但根本没有触及任何文件。所以我真的需要帮助......

附加信息是test.sh在后台运行:nohup test.sh &

有任何想法吗?谢谢

仅供参考:根据@xae 的建议,我是这样使用的:

nohup test.sh > /my.log 2>&1 &
while :; do (cat /my.log | grep "Watches established" > /dev/null) && break; done;
find "somedir" -type f -exec touch {} \+
Run Code Online (Sandbox Code Playgroud)

xae*_*xae 7

inotifywait输出字符串“ Watches created. ”时,可以安全地在被监视的 inode 中进行更改,因此您应该等待该字符串出现在标准错误中,然后再触摸文件。

例如,这段代码应该是这样的,

inotifywait -r -m -e close_write "somedir" \
2> >(while :;do read f; [ "$f" == "Watches established." ] && break;done;\
find "somedir" -type f -exec touch {} ";")\
| while read f; do echo "$f hi";done
Run Code Online (Sandbox Code Playgroud)