Linux - Watch a Directory for New Files, Then Run a Script

How to run a shell script when a file or directory changes?

Use inotify-tools.

The linked Github page has a number of examples; here is one of them.

#!/bin/sh

cwd=$(pwd)

inotifywait -mr \
--timefmt '%d/%m/%y %H:%M' --format '%T %w %f' \
-e close_write /tmp/test |
while read -r date time dir file; do
changed_abs=${dir}${file}
changed_rel=${changed_abs#"$cwd"/}

rsync --progress --relative -vrae 'ssh -p 22' "$changed_rel" \
usernam@example.com:/backup/root/dir && \
echo "At ${time} on ${date}, file $changed_abs was backed up via rsync" >&2
done

monitor a folder tree for changes and run a script when a file is created - linux

inotify is being around for a while, It's stable and is part of main stream of many distros.

How to install:

on Ubuntu:

sudo apt-get install inotify-tools

on Centos/RHEL (from EPEL repo):

yum --enablerepo epel install inotify-tools

How to use:

inotifywait -re create /tmp/test1/ && echo "Change detected"

Once you create a file echo "change detected" will be triggered which could be just about anything.

The output you get:

Setting up watches.  Beware: since -r was given, this may take a while!
Watches established.
/tmp/test1/test2/test3/ CREATE file
Change detected

PS. -r for recursive -e create to detect new files.

Monitor Directory for Changes

Look at inotify.

With inotify you can watch a directory for file creation.

Check directory daily for new files - linux bash script

You can use a daily cron job: http://linux.die.net/man/1/crontab



Related Topics



Leave a reply



Submit