簡體   English   中英

如何連續運行inotifywait並將其作為cron或deamon運行?

[英]How to run inotifywait continuously and run it as a cron or deamon?

我已經構建了一個shell腳本,該腳本使用inotifywait自動檢測特定目錄上的文件更改。 當將新的PDF文件放入目錄時,該腳本應關閉,然后應觸發ocropus-parser執行一些命令。 編碼:

#!/bin/sh
inotifywait -m ~/Desktop/PdfFolder -e create -e moved_to |
while read path action file; do
    #echo "The file '$file' appeared in directory '$path' via '$action'"
    # Check if the file is a PDF or another file type.
    if [ $(head -c 4 "$file") = "%PDF" ]; then
        echo "PDF found - filename: " + $file
        python ocropus-parser.py $file
    else
        echo "NOT A PDF!"
fi
done

當我使用./filenotifier.sh通過終端運行此腳本時,此方法運行良好,但是當我重新啟動Linux (Ubuntu 14.04)時,我的外殼將不再運行,並且在重新啟動后也不會重新啟動。 我決定創建一個在啟動時開始的初始化腳本(我認為)。 我是通過將文件filenotifier.sh復制到init.d

sudo cp ~/Desktop/PdfFolder/filenotifier.sh /etc/init.d/

然后,我給了文件正確的權限:

sudo chmod 775 /etc/init.d/filenotifier.sh

最后我將文件添加到update-rc.d

sudo update-rc.d filenotifier.sh defaults

但是,當我重新啟動並將PDF放到~/Desktop/PdfFolder文件夾中時,什么也不會發生,並且腳本似乎沒有關閉。 我真的沒有init.dupdate-rc.ddeamon經驗,所以我不確定什么是錯誤的,以及這是否是一個好的方法。

謝謝,Yenthe

  • 作為初始化腳本,您應將LSB標頭添加到腳本中,如下所示:

     #!/bin/sh ### BEGIN INIT INFO # Provides: filenotifier # Required-Start: $remote_fs $syslog # Required-Stop: $remote_fs $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Something # Description: Something else ### END INIT INFO inotifywait -m ... 

    這樣,您可以確保在所有安裝點都可用時運行腳本(由於Required-Start: $remote_fs )。 如果您的主目錄不在根分區上,則這是必不可少的。

  • 另一個問題是您的init腳本中使用的是~

     inotifywait -m ~/Desktop/PdfFolder ... 

    ~擴展到當前用戶的主目錄。 初始化腳本以root身份運行,因此它將擴展為/root/Desktop/PdfFolder 使用~<username>代替:

     inotifywait -m ~yenthe/Desktop/PdfFolder ... 

    (假設您的用戶名是yenthe 。)

    或者也許在啟動之前切換用戶(使用sudo )。

  • $file是沒有目錄路徑的基本名稱。 在命令中使用"$path/$file"

     "$(head -c 4 "$path/$file")" python ocropus-parser.py "$path/$file" 

    也許考慮使用name而不是file ,以避免混淆。

  • 如果事情不正常,或者一般來說您想研究一下,請記住使用ps ,如下所示:

     ps -ef | grep inotifywait 

    例如, ps會告訴您腳本是否正在運行以及是否使用正確的參數啟動了inotifywait

  • 最后但並非最不重要的一點:使用"$file" ,而不是$file ; 使用"$(head -c 4 "$file")" ,而不是$(head -c 4 "$file") 使用read -r而不是read 這些技巧可以在將來為您省去很多麻煩!

為此, inotify的開發人員創建了incron 這是一個類似於cron的守護程序,它根據監視的文件/目錄中的更改而不是時間事件來執行腳本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM