Since this is linux, you can rely on the inotifywait
utility, from the inotify-utils
package:
#!/bin/bash
FILES_TO_WATCH=("file1.txt" "file2.txt")
MERGED_FILE="merged.txt"
log() {
echo "[$(date -R)] $1" 1>&2
}
merge_files() {
log "Updating merged file"
sort -m "${FILES_TO_WATCH[@]}" > "$MERGED_FILE"
}
wait_for_changes() {
local changed_file
changed_file=$(inotifywait -qe modify "${FILES_TO_WATCH[@]}" --format "%w")
log "File '$changed_file' changed"
}
merge_files
while wait_for_changes; do
merge_files
done
Breakdown of the inotifywait
command:
-q
Be quiet, as opposed to logging status messages to stderr.
-e modify
Listen for the "modify" event. For other events, see man inotifywait
.
--format "%w"
Make it print only the filename when a modify event occurs.
${FILES_TO_WATCH[@]}
Expand the files on the FILES_TO_WATCH
array.