Skip to content

Instantly share code, notes, and snippets.

@fabswt
Last active February 23, 2024 19:26
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save fabswt/2799a21fcdb86a0587f74a81950d2c3a to your computer and use it in GitHub Desktop.
Save fabswt/2799a21fcdb86a0587f74a81950d2c3a to your computer and use it in GitHub Desktop.
Watch a directory using bash and inotifywait
#!/bin/sh
# Usage
#
# Call the script with the directory you want to watch as an argument. e.g.:
# watchdir.sh /app/foo/
#
#
# Description:
# Uses inotifywait to look for new files in a directory and process them:
# inotifywait outputs data which is passed (piped) to a do for subcommands.
#
#
# Requirements:
# Requires inotifywait which is part of inotify-tools.
# e.g. yum install -y inotify-tools or apt-get install -y inotify-tools.
#
#
# See also:
# https://linux.die.net/man/1/inotifywait
# https://github.com/inotify-tools/inotify-tools/wiki#info
# (Might be interested in pyinotify too.)
echo "Watch $1 for file changes..."
# Be careful not to confuse the output of `inotifywait` with that of `echo`.
# e.g. missing a `\` would break the pipe and write inotifywait's output, not
# the echo's.
inotifywait \
--monitor \
-e close_write $1 \
--timefmt '%Y-%m-%dT%H:%M:%S' \
--format '%T %w %f %e' \
| while read datetime dir filename event; do
echo "At $datetime $dir$filename changed $event"
echo "Now, we could use $datetime $dir $filename $event and pass them to some other command, too! e.g."
echo "python3 /app/phono.py --custom $dir$filename /tmp/$filename"
done
# --format:
# %T Replaced with the current Time in the format specified by the --timefmt option, which should be a format string suitable for passing to strftime(3).
# %w This will be replaced with the name of the Watched file on which an event occurred.
# %f When an event occurs within a directory, this will be replaced with the name of the File which caused the event to occur. Otherwise, this will be replaced with an empty string.
# %e Replaced with the Event(s) which occurred, comma-separated.
# %Xe Replaced with the Event(s) which occurred, separated by whichever character is in the place of 'X'.
# test the script by creating a file in the watched directory, e.g.
# touch /app/foo/file1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment