mirror of
https://git.decapod.one/brethil/dotfiles
synced 2024-11-21 11:01:31 +01:00
zsh: add watch_file command
uses inotifywait to watch writes on a file and executes a specific action whenever this is changed (killing the previous process)
This commit is contained in:
parent
25037bde1f
commit
10c79f1bad
|
@ -278,15 +278,43 @@ function mangrep() {
|
|||
|
||||
# watches the given file and executes the given action whenever the file is changed. Usage: watch_file <file> <command>
|
||||
function watch_file() {
|
||||
if ! which inotifywait &>/dev/null ; then echo "$0 requires inotifywait"; return 1; fi
|
||||
[[ -z "$1" ]] && "Usage: $0 <file> <action>" && return 1
|
||||
local file
|
||||
file="$1"
|
||||
if ! which inotifywait 2>&1 &>/dev/null ; then echo "$0 requires inotifywait"; return 1; fi
|
||||
|
||||
[[ -z "$1" ]] && echo "Usage: $0 <file> <action>" && return 1
|
||||
local file=$1
|
||||
shift
|
||||
|
||||
[[ -z "$@" ]] && "Usage: $0 <file> <action>" && return 1
|
||||
[[ -z "$@" ]] && echo "Usage: $0 <file> <action>" && return 1
|
||||
|
||||
local action
|
||||
action="$@"
|
||||
while inotifywait -e close_write "$file"; do zsh -c "$action"; done
|
||||
local action="$@"
|
||||
local _bg_job_pid
|
||||
|
||||
local TRAPINT(){
|
||||
|
||||
if [[ -n ${_bg_job_pid} ]]; then
|
||||
kill -9 ${_bg_job_pid}
|
||||
fi
|
||||
yellow '\nQuitting.'
|
||||
break;
|
||||
}
|
||||
|
||||
{
|
||||
set +m # disable job control messages
|
||||
while true; do
|
||||
zsh -c "$action" &
|
||||
_bg_job_pid=$!
|
||||
disown
|
||||
echo -e "$Cyan ==> Running \"$action\" with pid=${_bg_job_pid}$CLEAR"
|
||||
|
||||
# block until the file has been written to
|
||||
inotifywait -e close_write "$file" &>/dev/null
|
||||
|
||||
# the job might have failed, ignore errors
|
||||
kill -9 ${_bg_job_pid} &>/dev/null || true
|
||||
done
|
||||
} always {
|
||||
# remove ctrl-c trap
|
||||
unset -f TRAPINT
|
||||
set -m # restore job control messages
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user