เมื่อฉันต้องการตรวจจับการเปลี่ยนแปลงไฟล์และทำสิ่งอื่นที่ไม่ใช่สิ่งที่tail -f filenameฉันได้ใช้inotifywaitในสคริปต์เพื่อตรวจจับการเปลี่ยนแปลงและดำเนินการกับมัน ตัวอย่างการใช้งานแสดงไว้ด้านล่าง ดูman inotifywaitชื่อเหตุการณ์และสวิตช์อื่น ๆ คุณอาจจะต้องติดตั้งแพคเกจเช่นผ่านinotify-toolssudo apt-get install inotify-tools
นี่คือตัวอย่างสคริปต์ที่เรียกว่าexec-on-change:
#!/bin/sh
# Detect when file named by param $1 changes.
# When it changes, do command specified by other params.
F=$1
shift
P="$*"
# Result of inotifywait is put in S so it doesn't echo
while S=$(inotifywait -eMODIFY $F 2>/dev/null)
do
# Remove printf if timestamps not wanted
printf "At %s: \n" "$(date)"
$P
done
ในคอนโซลที่สองฉันป้อนคำสั่งดังนี้ (โดย A> หมายถึงรายการในคอนโซล A และ B> หมายถึงรายการในคอนโซล B. )
A> rm t; touch t
B> ./exec-on-change t wc t
A> date >>t
A> date -R >>t
A> date -Ru >>t
A> cat t; rm t
เอาต์พุตต่อไปนี้cat tปรากฏขึ้นในคอนโซล A:
Thu Aug 16 11:57:01 MDT 2012
Thu, 16 Aug 2012 11:57:04 -0600
Thu, 16 Aug 2012 17:57:07 +0000
เอาต์พุตต่อไปนี้exec-on-changeปรากฏขึ้นในคอนโซล B:
At Thu Aug 16 11:57:01 MDT 2012:
1 6 29 t
At Thu Aug 16 11:57:04 MDT 2012:
2 12 61 t
At Thu Aug 16 11:57:07 MDT 2012:
3 18 93 t
exec-on-changeสคริปต์สิ้นสุดลงเมื่อฉัน'drmt