LoginSignup
13
16

More than 5 years have passed since last update.

fswatchでディレクトリを監視,変更があればunisonで同期し,結果を通知する

Last updated at Posted at 2014-12-22

unisonの設定

~/.unison 以下に設定ファイル(.prf)を置く.
どっかのサイトの丸写しに近いものなので,説明は割愛.
sshの使い方も割愛.

Documents.prf
# コピー元ファイルのタイムスタンプも一緒にコピーする
times = true

# 新しいファイルを優先
prefer = newer

#新規作成ファイルはユーザに同期如何を問わない
auto = true

#ファイル更新日時による更新有無の判定
fastcheck = true

#エラー以外の出力停止
silent = true

# ルート・ディレクトリの指定。同期の際に最上位となるディレクトリを設定する。
root = /Users/kaz/
root = ssh://kaz//home/kaz/mac-backup/

# 同期したいディレクトリやファイル名を指定する
path = Documents

# 無視するディレクトリやファイル名を指定する。
ignore = Name *~
ignore = Name ._*
ignore = Name .DS_Store
ignore = Name *.bak

unison実行,及び通知するスクリプト

$1にさっきの設定ファイル(.prf)を拡張子なしで渡してやる.

~/Documents/exec/nortificate.sh
#!/bin/bash

unison "$1"

echo 'display notification "通知する文章" with title "タイトル" subtitle "サブタイトル"' | osascript

ファイル監視し,変更があれば上のスクリプトを実行するスクリプト

fswatchの使い方ほぼそのまま.
さっきの設定ファイル(.prf)を指定している.

fswatch_start.sh
#!/bin/bash

fswatch ~/Documents/ | xargs -I{} ~/Documents/exec/nortificate.sh "Documents" &

fswatchのUsageにはxargsの引数として -n1 も書かれているが,必要なさそう

fswatchからは変更があったファイルのパスがその都度返ってくる.そのため,-I{} としてそれをスルーしている.詳細は以下.

xargsについて

-I

-I{} は,コマンドの引数に含まれている{}を,標準入力で置換する.

例えば,

$ echo "piyo" | xargs -I "rep" echo "rep hoge piyo"`
piyo hoge piyo

となる.

-n1

-n1 は入力を1行毎に処理するというもの.
-n10 としておけば,10回入力がある度にコマンドを実行する.

ただ,-Iを含む時点でコマンドは一行ごとに実行されているような…

-I{} を指定せずに -n1 を指定して,fswatchの返り値をnortificate.shに渡せば,変更があった箇所も同時に通知するようにすることも出来る.

実際に使用しているスクリプト

実行と通知

通知するメッセージはunisonのドキュメントから引っ張ってきている.

~/Documents/exec/nortificate.sh
#!/bin/bash

unison "$1"

if [ $? -eq 0 ]; then
    echo 'display notification "successful synchronization; everything is up-to-date now." with title "unison '"$1"'" subtitle "'"$2"'"' | osascript
elif [ $? -eq 1 ]; then
    echo 'display notification "some files were skipped, but all file transfers were successful." with title "unison '"$1"'" subtitle "'"$2"'"' | osascript
elif [ $? -eq 2 ]; then
    echo 'display notification "non-fatal failures occurred during file transfer." with title "unison '"$1"'" subtitle "'"$2"'"' | osascript
elif [ $? -eq 3 ]; then
    echo 'display notification "a fatal error occurred, or the execution was interrupted." with title "unison '"$1"'" subtitle "'"$2"'"' | osascript
fi

変更の合った箇所(つまり同期した場所)と利用した設定ファイルも含めて通知する.

echo以下をシングルクォーテーションで囲まないと動かない?ため,引数を展開するために一旦シングルクォーテーションを抜けて引数を展開した後,再度囲む

というのも,シングルクォーテーションの中では$もそのまま文字列として扱われるためである.

監視とスクリプト実行

fswatch_start.sh
#!/bin/bash

fswatch ~/Documents/ | xargs -n1 ~/Documents/exec/nortificate.sh "Documents" &

設定ファイルと,変更があったファイルを渡している.

13
16
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
13
16