How to run a shell script when a file or directory

2019-01-04 21:40发布

I want to run a shell script when a specific file or directory changes.

How can I easily do that?

10条回答
SAY GOODBYE
2楼-- · 2019-01-04 22:29

I use this script to run a build script on changes in a directory tree:

#! /bin/bash
DIRECTORY_TO_OBSERVE="js"      // might want to change this
function block_for_change {
  inotifywait -r \
    -e modify,move,create,delete \
    $DIRECTORY_TO_OBSERVE
}
BUILD_SCRIPT=build.sh          // might want to change this too
function build {
  bash $BUILD_SCRIPT
}
build
while block_for_change; do
  build
done

Uses inotify-tools. Check inotifywait man page for how to customize what triggers the build.

查看更多
成全新的幸福
3楼-- · 2019-01-04 22:33

Here's another option: http://fileschanged.sourceforge.net/

See especially "example 4", which "monitors a directory and archives any new or changed files".

查看更多
Lonely孤独者°
4楼-- · 2019-01-04 22:38

Add the following to ~/.bashrc:

function react() {
    if [ -z "$1" -o -z "$2" ]; then
        echo "Usage: react <[./]file-to-watch> <[./]action> <to> <take>"
    elif ! [ -r "$1" ]; then
        echo "Can't react to $1, permission denied"
    else
        TARGET="$1"; shift
        ACTION="$@"
        while sleep 1; do
            ATIME=$(stat -c %Z "$TARGET")
            if [[ "$ATIME" != "${LTIME:-}" ]]; then
                LTIME=$ATIME
                $ACTION
            fi
        done
    fi
}
查看更多
对你真心纯属浪费
5楼-- · 2019-01-04 22:40

You may try entr tool to run arbitrary commands when files change. Example for files:

$ ls -d * | entr sh -c 'make && make test'

or:

$ ls *.css *.html | entr reload-browser Firefox

For directories use -d, but you've to use it in the loop, e.g.:

while true; do find path/ | entr -d echo Changed; done

or:

while true; do ls path/* | entr -pd echo Changed; done
查看更多
登录 后发表回答