シェルスクリプトで、ファイル更新したらコマンド実行する

ファイルの更新を監視し、更新されたらコマンドを実行するスクリプト。

inotifywaitが必要。ubuntuであれば以下でインストール。

apt-get install inotify-tools

スクリプトは以下。

#!/bin/bash
set -eu

#ファイルの更新を監視し、更新されたらコマンドを実行する。

if [ $# -ne 2 ]; then
    exefile_basename=`basename $0`;
    echo -e "too few argument."
    echo -e "\tusage : ${exefile_basename} (target file or dir) (commmand)"
    echo -e "\t        ${exefile_basename} code.c 'make test'"
    exit 1
fi

repeat_num=0
while true; do
    repeat_num=$((${repeat_num}+1))

    #コマンドエラーが起きても本スクリプトは終了しない。
    eval "$2" && true

    echo; echo "--------------------";
    echo "wait #$repeat_num"
    #隠しファイル(ドットで始まるもの)等は対象外。
    inotifywait -r --exclude '/\.|^\.[^./]' $1
    sleep 0.5
done

使い方は以下。

myinotify.sh ./code 'make; make test'

ディレクトリも対象にしているのでlsしたりしたときにも反応してしまう。
除きたいなら-eで監視するイベントを制限すれば良さそう。

スポンサーリンク

シェアする

  • このエントリーをはてなブックマークに追加

フォローする

スポンサーリンク