2012-08-13 63 views
3

我有一個斯芬克斯文檔的文件夾,我用inotifywait(從inotify-tools)看。該腳本重新構建html & singlehtml並刷新Chrome。使inotifywait組將多個文件更新合併爲一個?

#!/bin/sh 
inotifywait -mr source --exclude _build -e close_write -e create -e delete -e move | while read file event; do 
    make html singlehtml 
    xdotool search --name Chromium key --window %@ F5 
done 

這工作正常,當我保存單個文件。但是,當我在的舊版本中修改或粘貼source文件夾中的多個文件時,它會觸發的每個文件的腳本。

是否有一個簡單的解決方法(無需編寫自定義python腳本 - 我可以這樣做),使其在啓動腳本之前等待幾分之一秒?

回答

3

我做了一個稍微複雜一些的shell腳本,並張貼在the article

inotifywait -mr source --exclude _build -e close_write -e create -e delete -e move --format '%w %e %T' --timefmt '%H%M%S' | while read file event tm; do 
    current=$(date +'%H%M%S') 
    delta=`expr $current - $tm` 
    if [ $delta -lt 2 -a $delta -gt -2 ] ; then 
     sleep 1 # sleep 1 set to let file operations end 
     make html singlehtml 
     xdotool search --name Chromium key --window %@ F5 
    fi 
done 

它使inotifywait記錄不僅名&行動,但也時間戳。該腳本將時間戳與當前unixtime進行比較,如果增量小於2秒,則運行make html。但在此之前,它睡了1秒,讓文件操作結束。對於下一個修改後的文件,時間戳將是舊的,增量將超過2秒,並且不會執行任何操作。

我發現這種方式是最少的CPU消耗和最可靠的。

我也嘗試過運行一個簡單的Python腳本,但這意味着如果我將大到jQueryUI的東西粘貼到該文件夾​​中,則會產生一千個進程,然後變成殭屍。

1

嘗試這種情況:

last_update=0 
inotifywait -mr source --exclude _build -e close_write -e create \ 
    -e delete -e move --format '%T' --timefmt '%s' | 
    while read timestamp; do 
     sleep 1 
     if test $timestamp -ge $last_update; then 
      last_update=$(date +%s) 
      make html singlehtml 
      xdotool search --name Chromium key --window %@ F5 
     fi 
    done 
  1. --format '%T' --timefmt '%s'導致時間戳爲對於每個事件輸出。
  2. sleep 1被添加到等待事件積累。這裏的持續時間可能會更短,例如sleep 0.5,但它的便攜性會較差。
  3. test $timestamp -ge $last_update將事件時間戳與上次更新的時間戳進行比較。因此在睡眠期間發生的任何事件都被跳過。
  4. last_update=$(date +%s%N)設置時間戳以與下一個事件的時間戳進行比較。

注意,有一個競爭條件在這裏是因爲的strftime()不支持納秒。如果一組事件跨越第二個邊界,則此示例可以運行make兩次。爲了避免丟失事件,請將-ge替換爲-gt

相關問題