Today I Learned
Search…
Writing a simple file watcher using GNU Utils
Posted on 13 Dec, 2021
This simple file change watching script requires these two key utilities:
  1. 1.
    gdate
  2. 2.
    gstat
1
#!/usr/bin/env bash
2
​
3
set -eo pipefail
4
IFS=#x27;\n\t'
5
​
6
cleanup() {
7
# perform any post script completion tasks
8
printf "\n%s" "Cleanup Tasks ..."
9
exit
10
}
11
​
12
perform_task() {
13
# do stuff
14
printf "\n%s" "Performing Task ($(date +%I:%M:%S)) ..."
15
}
16
​
17
trap "cleanup" SIGINT
18
​
19
watch_changes() {
20
echo -en "\rWatching file $(tput bold)$1$(tput sgr0) ...\n"
21
while true; do
22
past_modify_time=$(gdate -d "@$(gstat -c '%Y' "$1")" '+%T')
23
# sleep for 100 milliseconds
24
sleep 0.1
25
new_modify_time=$(gdate -d "@$(gstat -c '%Y' "$1")" '+%T')
26
​
27
[[ "$past_modify_time" != "$new_modify_time" ]] && perform_task
28
done
29
}
30
​
31
if [[ -z "$1" ]]; then
32
echo -e "requires a file as an argument"
33
exit 1
34
else
35
watch_changes "$1"
36
fi
Copied!
Copy link
Edit on GitHub