我有一个目录/ nfs / old_home / dexter / work / Deamon / Test2 / IN /
有某些文件移入IN /目录,是否有任何方法可以检查该目录中的文件并对其执行某些操作?
例如,我想在那些文件上运行一些命令,那么如何使用shell脚本实现它?
答案 0 :(得分:0)
如果无法安装文件监视器实用程序,则必须轮询更改。
您可以定期调用执行以下操作的脚本:
#!/bin/bash
timestamp=/path/to/my/timestamp/file
timestamp2=/path/to/my/timestamp/file2
work=/nfs/old_home/path/stuff
# We want to look for things that are newer than timestamp.
# First time round, timestamp won't exist, so we just quit.
[ -f "$timestamp" ] || { touch "$timestamp" "$timestamp2"; exit; }
# On subsequent calls, we get a list of "newer" files and
# do something to them.
# Example 1: pass as many files are possible to a command:
find "$work/" -cnewer "$timestamp" -type f -print0 |\
xargs -0 /my/command
# Example 2: do something more complicated:
find "$work/" -cnewer "$timestamp" -type f -print0 |\
while read -d $'\000' -r file; do
/my/command "$file" -some-options | /my/other/command -stuff
done
# once finished, update timestamp so we won't process these
# files again.
touch "$timestamp"
# There is a race condition - new files could come in after
# we start processing but before we update timestamp.
# Use timestamp2 to check for these.
find "$work/" -cnewer "$timestamp2" -type f -print0 |\
xargs -0 /my/command
# Update this timestamp too.
# Anything that may come in while we are processing this batch
# will be handled next time.
touch "$timestamp2"
# if running via a scheduler (eg. cron), just quit now
exit
要连续循环检查,我们可以执行以下操作:
#!/bin/bash
timestamp=/path/to/my/timestamp/file
timestamp2=/path/to/my/timestamp/file2
work=/nfs/old_home/path/stuff
[ -f "$timestamp" ] || { touch "$timestamp" "$timestamp2"; }
# re-check every 5 minutes
while sleep 600; do
for ts in "$timestamp" $"timestamp2"; do
find "$work/" -cnewer "$ts" -type f -print0 |\
xargs -0 /my/command
touch "$ts"
done