代码之家  ›  专栏  ›  技术社区  ›  Ian Vaughan

监视文件夹中文件更改的Linux脚本(如autospec!)

  •  17
  • Ian Vaughan  · 技术社区  · 14 年前

    我想在文件更改时自动启动生成。

    我在Ruby中使用了autospec(rspec),我很喜欢它。

    如何在bash中完成这项工作?

    6 回复  |  直到 8 年前
        1
  •  14
  •   Dennis Williamson    14 年前
        2
  •  5
  •   zed_0xff    14 年前

    关键字是inotifywait&inotifywatch命令

        3
  •  5
  •   Ian Vaughan    11 年前

    在阅读了其他帖子的回复后,我发现了一篇帖子(现在不见了),我创建了这个脚本:

    #!/bin/bash
    
    sha=0
    previous_sha=0
    
    update_sha()
    {
        sha=`ls -lR . | sha1sum`
    }
    
    build () {
        ## Build/make commands here
        echo
        echo "--> Monitor: Monitoring filesystem... (Press enter to force a build/update)"
    }
    
    changed () {
        echo "--> Monitor: Files changed, Building..."
        build
        previous_sha=$sha
    }
    
    compare () {
        update_sha
        if [[ $sha != $previous_sha ]] ; then changed; fi
    }
    
    run () {
        while true; do
    
            compare
    
            read -s -t 1 && (
                echo "--> Monitor: Forced Update..."
                build
            )
    
        done
    }
    
    echo "--> Monitor: Init..."
    echo "--> Monitor: Monitoring filesystem... (Press enter to force a build/update)"
    run
    
        4
  •  5
  •   Ian Vaughan    11 年前

    这个剧本怎么样?使用“stat”命令获取文件的访问时间,并在访问时间发生更改时(访问文件时)运行命令。

    #!/bin/bash
    while true
    do
       ATIME=`stat -c %Z /path/to/the/file.txt`
       if [[ "$ATIME" != "$LTIME" ]]
       then
           echo "RUN COMMNAD"
           LTIME=$ATIME
       fi
       sleep 5
    done
    
        5
  •  2
  •   kenorb    8 年前

    如果你已经 entr 已安装,然后在shell中可以使用以下语法:

    while true; do find src/ | entr -d make build; done
    
        6
  •  2
  •   kenorb    8 年前

    this 伊恩·沃恩的回答改进实例:

    #!/usr/bin/env bash
    # script:  watch
    # author:  Mike Smullin <mike@smullindesign.com>
    # license: GPLv3
    # description:
    #   watches the given path for changes
    #   and executes a given command when changes occur
    # usage:
    #   watch <path> <cmd...>
    #
    
    path=$1
    shift
    cmd=$*
    sha=0
    update_sha() {
      sha=`ls -lR --time-style=full-iso $path | sha1sum`
    }
    update_sha
    previous_sha=$sha
    build() {
      echo -en " building...\n\n"
      $cmd
      echo -en "\n--> resumed watching."
    }
    compare() {
      update_sha
      if [[ $sha != $previous_sha ]] ; then
        echo -n "change detected,"
        build
        previous_sha=$sha
      else
        echo -n .
      fi
    }
    trap build SIGINT
    trap exit SIGQUIT
    
    echo -e  "--> Press Ctrl+C to force build, Ctrl+\\ to exit."
    echo -en "--> watching \"$path\"."
    while true; do
      compare
      sleep 1
    done