Last active
February 3, 2019 17:58
-
-
Save hatappo/fc060f0d7564191ae97a08818ec19a37 to your computer and use it in GitHub Desktop.
ファイル(群)の変更を検知して、自動的にコマンドを実行するシェルスクリプト
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
#################### | |
# Usage | |
#################### | |
if [ $# -lt 2 ]; then | |
echo "Usage: | |
第一引数: 監視対象ファイルが更新された際に実行されるコマンド | |
第二引数以降: 監視対象ファイルのリスト | |
例: $0 'cargo build && cargo run' ./src/*.rs | |
$0 'mermaid -sp \$_f' ./*.mermaid | |
" | |
exit 1 | |
fi | |
#################### | |
# Functions | |
#################### | |
LOGLEVEL=${LOGLEVEL:-1} | |
LOGLEVELS=( DEBUG INFO WARN ) | |
function log() { | |
local level=$1 | |
shift | |
if [ $level -ge $LOGLEVEL ]; then | |
printf "`date +'%Y-%m-%d_%T'` %7s %s\n" "[${LOGLEVELS[$level]}]" "$*" | |
fi | |
} | |
function debug() { log 0 "$*"; } | |
function info() { log 1 "$*"; } | |
function warn() { log 2 "$*"; } | |
#################### | |
# Variables | |
#################### | |
INTERVAL=${INTERVAL:-1} # 変更をチェックする間隔。単位は秒。 | |
COMMAND=$1 # 変更を検知した際に実行するコマンド。 | |
shift | |
WATCHFILES=() # 監視対象ファイルのリスト | |
timestamps=() # 監視対象ファイルの更新日時のリスト | |
for f in "$@"; do | |
if [ -f "$f" ]; then | |
WATCHFILES+=( "$f" ) | |
timestamps+=( `ls -lT $f | awk '{print $9"-"$6"-"$7"_"$8}'` ) | |
else | |
warn " Ignored: '$f'" 1>&2 | |
fi | |
shift | |
done | |
info " | |
INTERVAL: $INTERVAL (sec) | |
COMMAND: $COMMAND | |
WATCHFILES: ${WATCHFILES[@]} | |
timestamps: ${timestamps[@]} | |
" | |
#################### | |
# Main | |
#################### | |
from=0 | |
to=$((${#WATCHFILES[@]} - 1)) | |
while true; do | |
sleep $INTERVAL | |
for i in `seq $from $to`; do | |
_f=${WATCHFILES[$i]} | |
_last=${timestamps[$i]} | |
_current=`ls -lT $_f | awk '{print $9"-"$6"-"$7"_"$8}'` | |
timestamps[$i]=$_current | |
debug $_f | |
debug $_last | |
debug $_current | |
if [ $_last != $_current ]; then | |
info "File: '$_f' was changed" | |
info "Command: '$COMMAND' is executed." | |
_last=$_current | |
eval $COMMAND | |
echo "" | |
fi | |
done | |
done |
http://hatappo.hatenadiary.jp/entry/2016/07/18/183039
gulp.watchみたいな「ファイルの変更を検知して何かする」をShellで手軽にやりたい - (-> % read write unlearn)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
参考