使用inotifywait并行处理两个文件

时间:2016-03-16 18:29:49

标签: linux bash monitoring inotifywait

我正在使用:

inotifywait -m -q -e close_write --format %f . | while IFS= read -r file; do
cp -p "$file" /path/to/other/directory
done

监控文件夹的文件完成情况,然后将其移至另一个文件夹。

文件是成对的,但是在不同的时间,即File1_001.txt在下午3点制作,File1_002.txt在晚上9点制作。我想监视BOTH文件的完成情况,然后启动一个脚本。

script.sh File1_001.txt File1_002.txt

所以我需要另外一个inotifywait命令或一个不同的实用程序,它们还可以识别这两个文件是否存在并完成,然后启动脚本。

有谁知道如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我找到了一个安装了inotifywait的Linux机箱,所以现在我明白了它的作用以及它是如何工作的。 :)

这是你需要的吗?

#!/bin/bash

if [ "$1" = "-v" ]; then
        Verbose=true
        shift
else
        Verbose=false
fi

file1="$1"
file2="$2"

$Verbose && printf 'Waiting for %s and %s.\n' "$file1" "$file2"

got1=false
got2=false
while read thisfile; do
        $Verbose && printf ">> $thisfile"
        case "$thisfile" in
                $file1) got1=true; $Verbose && printf "... it's a match!" ;;
                $file2) got2=true; $Verbose && printf "... it's a match!" ;;
        esac
        $Verbose && printf '\n'
        if $got1 && $got2; then
                $Verbose && printf 'Saw both files.\n'
                break
        fi
done < <(inotifywait -m -q -e close_write --format %f .)

这会运行单个inotifywait,但会在一个循环中解析其输出,当命令行($1$2)上的两个文件都被更新时,它会退出。

请注意,如果关闭一个文件,然后在第二个文件关闭时重新打开,则此脚本显然不会检测到打开的文件。但这可能不是您用例中的问题。

请注意,有很多方法可以构建解决方案 - 我只向您展示了一个解决方案。