File Watcher in Shell

Level 5250 keystrokes

inotifywait (Linux, from inotify-tools) watches ./src and prints one line per change; a while loop reads each event and reacts to it, for example by running a build. It keeps running until it is stopped; the output depends on the changes made.

Shell code

# Directory to watch
1watch_dir="./src"
# -m keeps watching, -r includes subdirectories, -e picks the events
# Each event is printed as: DIRECTORY EVENT FILE
2inotifywait -m -r -e modify,create,delete "$watch_dir" |
# The pipe feeds each event line to read, which splits it into three variables
3while read path action file; do
# Log the event, e.g. [MODIFY] ./src/app.js
4 echo "[$action] $path$file"
# Choose an action by event type; * also matches names like CREATE,ISDIR
5 case $action in
# Rebuild when a file changes
6 MODIFY*) npm run build ;;
7 CREATE*) echo "New: $file" ;;
8 DELETE*) echo "Removed: $file" ;;
9 esac
10done

Output

[MODIFY] ./src/app.js
[CREATE] ./src/utils.js
New: utils.js
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Shell code and how often they appear.

  • "× 10
  • ;× 7
  • $× 7
  • -× 3
  • )× 3
  • *× 3
  • _× 2
  • ,× 2
  • :× 2
  • .× 1

More Shell examples at level 5

← Shell typing practice