bash 监视文件夹内文件更改的 linux 脚本(就像 autospec 一样!)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2972765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
linux script that monitors file changes within folders (like autospec does!)
提问by Ian Vaughan
I want to automatically kick off a build whenever a file changes.
我想在文件更改时自动启动构建。
I've used autospec (RSpec) in Ruby and loved that.
我在 Ruby 中使用过 autospec (RSpec) 并且喜欢它。
How can this be done in bash?
这如何在 bash 中完成?
采纳答案by Ian Vaughan
After reading replies to other posts, I found a post (now gone), I created this script :-
在阅读了其他帖子的回复后,我找到了一个帖子(现在不见了),我创建了这个脚本:-
#!/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
回答by Paused until further notice.
Take a look at incronand inotify-tools.
回答by VDR
How about this script? Uses the 'stat' command to get the access time of a file and runs a command whenever there is a change in the access time (whenever file is accessed).
这个剧本怎么样?使用 '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
回答by zed_0xff
keywords are inotifywait & inotifywatch commands
关键字是 inotifywait 和 inotifywatch 命令
回答by Mike S
See thisexample as an improvement upon on Ian Vaughan's answer:
见这个例子作为对伊恩·沃恩的回答有所改善:
#!/usr/bin/env bash
# script: watch
# author: Mike Smullin <[email protected]>
# license: GPLv3
# description:
# watches the given path for changes
# and executes a given command when changes occur
# usage:
# watch <path> <cmd...>
#
path=
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