LoginSignup
1
1

More than 5 years have passed since last update.

JSONファイルの変更を監視して差分を表示するシェルスクリプト

Posted at

JSONファイルの変更を監視して、変更が発生したら差分を表示する簡単なシェルスクリプトを書いた。
データをJSONファイルに保存する処理の開発・デバッグに使うと良いです。

ファイルの日付を見て変更を監視し、node.jsで引数のjsonを出力形式を整えてdiffに渡している。
外部モジュールのインストール不要なのがメリット。

macOS High Sierraとmojaveで動作確認したがnode.jsとshellが動けば動くと思われる。
なお、引数のファイルパスは拡張子を.json(大文字でもOK)にする必要があります。

参考:
- https://qiita.com/tamanobi/items/74b62e25506af394eae5
- https://fumiyas.github.io/2013/12/06/tempfile.sh-advent-calendar.html
- https://qiita.com/hirobe/items/c7845fd3b6f9177e604f

watchjson.sh
#!/bin/sh

if [ $# -ne 1 ]; then
    echo "Usage:"
    echo "./watchjson.sh filepath.json"
    exit 1
fi
INTERVAL=1 # sec
last=`ls -l -T "$1" | awk '{print $8}'`
tmpfile=`mktemp`.json
cp "$1" $tmpfile

atexit() {
  [[ -n ${tmpfile-} ]] && rm "$tmpfile"
}
trap atexit EXIT
trap 'rc=$?; trap - EXIT; atexit; exit $?' INT PIPE TERM

while true; do
    sleep $INTERVAL
    current=`ls -l -T "$1" | awk '{print $8}'`
    if [ $last != $current  ] ; then
        echo ""
        echo "updated: $current"
        last=$current
        node -e "console.log(JSON.stringify(require('$tmpfile'),null,2))" | (node -e "console.log(JSON.stringify(require('$1'),null,2))" | diff /dev/fd/3 -) 3<&0 
        cp "$1" $tmpfile
    fi
done

 使い方

$ ./watchjson.sh jsonのパス

出力例:

updated: 12:05:01
166c166
<       "schedule": "",
---
>       "schedule": "スケジュール",

updated: 12:05:04
179c179
<       "items": "",
---
>       "items": "アイテム",

おまけ

上記シェルスクリプトはjsonファイル専用ですが、ちょっと変更するとjson以外のテキストファイルの差分監視ができます。
こんな感じ

watchdiff.sh
#!/bin/sh

if [ $# -ne 1 ]; then
    echo "Usage:"
    echo "./watchdiff.sh filepath"
    exit 1
fi
INTERVAL=1 # sec
last=`ls -l -T "$1" | awk '{print $8}'`
tmpfile=`mktemp`
cp "$1" $tmpfile

atexit() {
  [[ -n ${tmpfile-} ]] && rm "$tmpfile"
}
trap atexit EXIT
trap 'rc=$?; trap - EXIT; atexit; exit $?' INT PIPE TERM

while true; do
    sleep $INTERVAL
    current=`ls -l -T "$1" | awk '{print $8}'`
    if [ $last != $current  ] ; then
        echo ""
        echo "updated: $current"
        last=$current
        diff $tmpfile $1
        cp "$1" $tmpfile
    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