LoginSignup
6
6

More than 5 years have passed since last update.

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

Last updated at Posted at 2017-02-22

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

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

apt-get install inotify-tools

スクリプトは以下。

myinotify.sh
#!/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で監視するイベントを制限すれば良さそう。

6
6
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
6
6