LoginSignup
17
15

More than 5 years have passed since last update.

Bashで、ファイルが変更されたら特定のコマンドを実行する

Last updated at Posted at 2016-09-13

これ、やりたかった。

GuardGulp等で解決できる話だが、それを使うまででもないような作業に重宝する。

$HOME/bin/exec_on_change
#!/bin/bash

usage(){
    echo "Usage:"
    echo "    exec_on_change file command"
    exit 1
}

die(){
    echo $1
    exit 2
}

[ $# -lt 2 ] && usage
[ -e "$1" ] || die "No such file or directory: $1"

while true; do
    inotifywait "$1" 2>/dev/null || exit
    $2
done

最後の4行がミソ。
最近のLinuxならこれで良いはず。導入にはinotify-toolsが必要。

sudo apt-get install inotify-tools

使い方

ファイル変更検知

$ exec_on_change /tmp/a 'echo File changed'

# 別シェルで、ファイルを変更
$ date > /tmp/a
# => /tmp/a MODIFY 
# => File changed

ディレクトリもいける

$ exec_on_change /tmp/ 'echo File changed'

これで、テスト駆動開発がはかどる。

追記

2番めの引数で指定するコマンドで、パイプが使えない・・・

=> evalを使って、使えるようにしました。

zshのプラグインにしてみました。

antigenを使うか、source init.zshして下さい。

antigen bundle acro5piano/exec_on_change

更に追記

Emacsのflymakeとかでできるんじゃないか説

17
15
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
17
15