sudo apt install inotify-tools
In a shell enter:
while true; do res=`inotifywait -r thedirtowatch/ --format %f`; echo "RESULT=$res"; done
returns:
Setting up watches. Beware: since -r was given, this may take a while! Watches established.
NOTE: The --format %f refers to the filename in the event.
See http://manpages.ubuntu.com/manpages/focal/man1/inotifywait.1.html for options.
In a 2nd shell, go to that directory being watched.
cd thedirtowatch/ touch test1
NOTE: Back on the 1st shell this should show you output:
RESULT=test1
Change the inotifywait to the following:
while true; do res=`inotifywait -q -e create, open, close, modify, moved_to, moved_from -r thedirtowatch/ --format '%e %f'`; echo "RESULT=$res\n"; done
NOTE: The additional -e option can be added to the inotifywait to only listen for certain events.
Events include:
The --format option is changed to include showing %e which is the actual event. Obviously change as needed.
The -q option is to not show too much output.
See http://manpages.ubuntu.com/manpages/focal/man1/inotifywait.1.html for options.
Instead of running in a while true; do loop, an alternative is to use monitor mode:
inotifywait -m thedirtowatch/ -e create -e moved_to | while read dir action file; do echo "The file '$file' appeared in directory '$dir' via '$action'" # do something with the file. done
NOTE: The --format %f refers to the filename in the event.
See http://manpages.ubuntu.com/manpages/focal/man1/inotifywait.1.html for options.
#!/bin/bash # # Monitor the input directory and if any change occurs run the provided command: # # Usage: # after-change.sh /tmp ls -al %f if [ $# -lt 3 ]; then echo "Usage: $0 dir cmd " exit 1 fi which inotifywait 2>&1 >/dev/null if [ "$?" == "1" ]; then echo "ERROR: inotifywait not installed." exit 1 fi dir=$1 shift cmd=$1 shift options=$* inotifywait -q -r -m $dir $options eval $cmd