如何監控文件是否已建立?

如何監控文件是否已建立?

例如,我需要監視是否文件/tmp/somefile123是在一些事件之後創建的。我嘗試使用inotify等待但這裡有一個問題:

# inotifywait -q -e create /tmp/somefile?*
Couldn't watch /tmp/somefile?*: No such file or directory

因為根本不存在這樣的文件,我想知道它是否會在那裡!

我該如何解決這個問題?

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

我預計該腳本將停止執行inotifywait -e 建立 $SPECIFIC_FILE直到這個 $SPECIFIC_FILE 不會被創建,然後會更好

while [ ! -f $SPECIFIC_FILE ]; do
    blah-blah-blah some actions
    sleep 1
done

答案1

有了inotify等待檢查父目錄

/tmp$ inotifywait -e create -d -o /home/me/zz /tmp
/tmp$ touch z1
/tmp$ cat ~/zz
/tmp/ CREATE z1

您也可以使用以下命令指定事件的時間格式-timefmt選項。另外,如果您想透過執行某些腳本檔案立即採取行動,例如,您可以使用尾部-f在腳本文件中連續監控日誌文件,這裡/家/我/zz,或者您可以建立一個命名管道文件並有inotify等待寫入它,而您的腳本從中讀取。

相關內容