Jared Taylor
Jared Taylor

Reputation: 13

Using inotifywait to process two files in parallel

I am using:

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

to monitor a folder for file completion, then moving it to another folder.

Files are made in pairs but at separate times, ie File1_001.txt is made at 3pm, File1_002.txt is made at 9pm. I want to monitor for the completion of BOTH files, then launch a script.

script.sh File1_001.txt File1_002.txt

So I need to have another inotifywait command or a different utility, that can also identify that both files are present and completed, then start the script.

Does anyone know how to solve this problem?

Upvotes: 0

Views: 1025

Answers (1)

ghoti
ghoti

Reputation: 46816

I found a Linux box with inotifywait installed on it, so now I understand what it does and how it works. :)

Is this what you need?

#!/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 .)

This runs a single inotifywait but parses its output in a loop that exits when both files on the command line ($1 and $2) are seen to have been updated.

Note that if one file is closed and then later is reopened while the second file is closed, this script obviously will not detect the open file. But that may not be a concern in your use case.

Note that there are many ways of building a solution -- I've shown you only one.

Upvotes: 1

Related Questions