如何监控文件是否被创建?

Her*_*rth 2 monitoring files inotify

例如,我需要监视文件/tmp/somefile123是否是在某些事件之后创建的。我尝试使用inotifywait但这里有一个问题:

# inotifywait -q -e create /tmp/somefile?*
Couldn't watch /tmp/somefile?*: No such file or directory
Run Code Online (Sandbox Code Playgroud)

因为完全没有这样的文件,我想知道它是否会在那里!

我该如何解决这个问题?

UPD:也许如果我解释一下我想要达到的目标会更清楚。

我需要以最少的 CPU 消耗编写 shell 脚本 (sh),如下所示:

if [ $(inotifywait -e create $SPECIFIC_FILE) ]; then
    blah-blah-blah some actions
fi
# And then similarly monitor if this file was deleted and then do another actions
Run Code Online (Sandbox Code Playgroud)

我希望脚本会在inotifywait -e create $SPECIFIC_FILE上停止执行,直到这个 $SPECIFIC_FILE 不会被创建,然后会更好

while [ ! -f $SPECIFIC_FILE ]; do
    blah-blah-blah some actions
    sleep 1
done
Run Code Online (Sandbox Code Playgroud)

Mar*_*iae 6

通过inotifywait检查父目录

/tmp$ inotifywait -e create -d -o /home/me/zz /tmp
/tmp$ touch z1
/tmp$ cat ~/zz
/tmp/ CREATE z1
Run Code Online (Sandbox Code Playgroud)

您还可以使用-timefmt选项指定事件的时间格式。另外,如果您想通过执行某个脚本文件立即采取行动,例如,您可以在脚本文件中使用tail -f来持续监视日志文件,这里是/home/me/zz,或者您可以创建一个命名管道文件并让inotifywait写入它,而您的脚本从中读取。

  • @HeroFromEarth 我很抱歉,但我上面的回答完全符合您在 OP 和更新中所说的内容。你为什么相信它没有? (2认同)