-
-
Save sc0ttj/67c859dd5f83eb03893836c4825789e1 to your computer and use it in GitHub Desktop.
Watch a directory using bash and inotifywait
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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