Skip to content

Instantly share code, notes, and snippets.

@leite
Created June 9, 2023 13:50
Show Gist options
  • Save leite/9e02c0d1d10b392e2f8af7a8b774e6b8 to your computer and use it in GitHub Desktop.
Save leite/9e02c0d1d10b392e2f8af7a8b774e6b8 to your computer and use it in GitHub Desktop.
check if files change timestamp in path
#!/usr/bin/env bash
declare -A cached_paths
declare -A processed_paths
cache=$(echo ${TMPDIR:-/tmp})
err () {
>&2 echo "$1"
exit 1
}
read_cache () {
test -f $cache || {
test -d $cache && {
cache="$cache/.mon.cache"
touch $cache
} || {
err "cache does not exists $cache"
}
}
while read -r timestamp path; do
cached_paths[$path]=$timestamp
done < $cache
}
assert_data () {
:> $cache
alert=""
for path in "${!processed_paths[@]}"; do
IFS=, read -r timestamp filepath datetime <<< "${processed_paths[$path]}"
[[ ! -z "${cached_paths[$path]}" && "${cached_paths[$path]}" != "$timestamp" ]] && {
alert="file $filepath changed at $datetime"
}
echo "$timestamp $path" >> $cache
done
test -z "$alert" || err "$alert"
}
process_paths () {
for path in "${!cached_paths[@]}"; do
processed_paths[$path]="${cached_paths[$path]}"
done
for path in $paths; do
test -d $path || err "path $path does not exists"
processed_paths[$path]=$(find $path -type f $excludes -exec stat {} --printf="%Y,%n,%y\n" \; 2>/dev/null | sort -n -r | head -1)
done
}
usage () {
cat << HELP
options:
-c /path/... cache path
-p /path/to path to monitor
-e /another/path path to exclude
-a alert mode
-h this help
examples:
$0 -a -p /var/www/html/app -p /var/www/html/super_app -e storage/cache
$0 -a -c /var/cache/mon.cache -p /var/www/html
$0 -h
about:
monitors changes in files timestamp of give path(s) [-p] excluding path(s) [-e] if
supplied with [-e] option, [-a] alert mode will send alert to ..., if you dont
supply [-a], it will generate a cache (in [-c] location if supplied) and wont
alert;
HELP
exit 0
}
while getopts "c:p:e:ah" o; do
case "${o}" in
c) cache="${OPTARG}" ;;
p) paths="$paths ${OPTARG}" ;;
e) excludes="$excludes -not -path \"*${OPTARG}*\"" ;;
*|h) usage ;;
esac
done
shift $((OPTIND-1))
read_cache
process_paths
assert_data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment