Skip to content

Instantly share code, notes, and snippets.

@AlexAtkinson
Last active January 5, 2024 21:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlexAtkinson/53f2d75d2f1da3c83e8dcd68150367cc to your computer and use it in GitHub Desktop.
Save AlexAtkinson/53f2d75d2f1da3c83e8dcd68150367cc to your computer and use it in GitHub Desktop.
Detects changes in a file.
#!/usr/bin/env bash
# file_watch.sh
# ------------------------------------------------------------------------------
# Description:
# Watches a file for changes.
# Includes output on inode changes as that may be desirable in some scenarios.
# NOTE: ... Just use inotifywait.
#
# Usage:
# ./file_watch <path/to/file>
#
# Example:
# Reload a config file automatically while editing it:
# NOTE: See this article if you want to use inodewait.
# - https://cyral.com/blog/how-to-auto-reload-nginx/
# while read line; do
# if [[ $line =~ "change" ]]; then
# nginx -t && /etc/init.d/nginx reload
# fi
# done< <(./file_watch.sh /etc/nginx/conf.d/default.conf)
# ------------------------------------------------------------------------------
file=$1
function logger2() {
[[ $1 -eq 0 ]] && echo -e "$(date --utc +'%FT%T.%3NZ') - \e[01;30;41mEMERGENCY\e[0m: ${*:2}"
[[ $1 -eq 1 ]] && echo -e "$(date --utc +'%FT%T.%3NZ') - \e[01;31;43mALERT\e[0m: ${*:2}"
[[ $1 -eq 2 ]] && echo -e "$(date --utc +'%FT%T.%3NZ') - \e[01;97;41mCRITICAL\e[0m: ${*:2}"
[[ $1 -eq 3 ]] && echo -e "$(date --utc +'%FT%T.%3NZ') - \e[01;31mERROR\e[0m: ${*:2}"
[[ $1 -eq 4 ]] && echo -e "$(date --utc +'%FT%T.%3NZ') - \e[01;33mWARNING\e[0m: ${*:2}"
[[ $1 -eq 5 ]] && echo -e "$(date --utc +'%FT%T.%3NZ') - \e[01;30;107mNOTICE\e[0m: ${*:2}"
[[ $1 -eq 6 ]] && echo -e "$(date --utc +'%FT%T.%3NZ') - \e[01;39mINFO\e[0m: ${*:2}"
[[ $1 -eq 7 ]] && echo -e "$(date --utc +'%FT%T.%3NZ') - \e[01;97;46mDEBUG\e[0m: ${*:2}"
[[ $1 -eq 9 ]] && echo -e "$(date --utc +'%FT%T.%3NZ') - \e[01;32mSUCCESS\e[0m: ${*:2}"
}
if [[ $# -ne 1 ]]; then
logger2 3 "Exactly 1 argument is required. It MUST be an existing file."
exit 1
fi
if [[ ! -f $file ]]; then
logger2 3 "The path provided is not a file."
fi
get_file_inode() {
stat -c '%i' "$file"
}
detect_inode_change() {
if [[ "$file_inode" != $(get_file_inode) ]]; then
logger2 4 "inode change detected in file: $file"
#exit 1
file_inode=$(get_file_inode)
fi
}
get_file_md5sum() {
md5sum "$file" | awk '{print $1}'
}
detect_md5sum_change() {
if [[ "$file_md5sum" != $(get_file_md5sum) ]]; then
logger2 4 "md5sum change detected in file: $file"
# exit 1
file_md5sum=$(get_file_md5sum)
fi
}
file_inode=$(get_file_inode)
file_md5sum=$(get_file_md5sum)
while true; do
detect_inode_change
detect_md5sum_change
sleep 1
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment