LoginSignup
1
1

More than 5 years have passed since last update.

ファイル変更監視してコマンド実行するやつ

Posted at

元ネタ
ファイルの変更を定期的に監視して、特定のコマンドを実行するシェルスクリプト

Eclipse で war 監視してたら書き込み中も判定されてしまったので少し直した。

#!/bin/sh
# see also http://mizti.hatenablog.com/entry/2013/01/27/204343
usage() {
  echo "実行するには2個の引数が必要です。
  第一引数: 監視対象ファイル名
  第二引数: 監視対象ファイルが更新された際に実行されるコマンド
  例: ./autoexec.sh a.cpp 'g++ a.cpp && ./a.cpp'"
}
update() {
  echo `openssl sha256 -r $1 | awk '{print $1}'`
}
if [ $# -ne 2 ];
then
  usage
  exit 1
fi

INTERVAL=1 #監視間隔, 秒で指定
last=`update $1`
echo "Watching... file: $1"
while true;
do
  sleep $INTERVAL
  current=`update $1`
  lsof=`lsof -f -- $1`
  if [ "$last" != "$current" ]; then
    nowdate=`date '+%Y/%m/%d'`
    nowtime=`date '+%H:%M:%S'`
    echo "$nowdate $nowtime : detected update of file: $1"
    if [ -n "$lsof" ]; then
      echo "=> Skipping, $1 is opened by other process..."
    else
      echo "=> Executing Command : $2"
      eval $2
      echo "\nWatching... file: $1"
    fi
    last=$current
  fi
done
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1