diff --git a/functions/misc.zsh b/functions/misc.zsh index 4277a32..8b2ea82 100755 --- a/functions/misc.zsh +++ b/functions/misc.zsh @@ -278,15 +278,43 @@ function mangrep() { # watches the given file and executes the given action whenever the file is changed. Usage: watch_file function watch_file() { - if ! which inotifywait &>/dev/null ; then echo "$0 requires inotifywait"; return 1; fi - [[ -z "$1" ]] && "Usage: $0 " && 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 " && return 1 + local file=$1 shift - [[ -z "$@" ]] && "Usage: $0 " && return 1 + [[ -z "$@" ]] && echo "Usage: $0 " && 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 + } }