5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ファイルを監視して、変更されたらコピーする。

Posted at

複数のファイルを監視して、どれか1つでも更新されたら指定したディレクトリにコピーします。
Dropboxにバックアップするのに使ってます。

copy_file_when_modified.zsh
#!/bin/zsh -f                                                                                                                 
if [[ $# < 2 ]]; then
    echo "Copy file to a directory when any one of files was modified." >&2
    echo "usage: `/usr/bin/basename $0` destDir(Such as DropBoxDir) file1 file2 ..." >&2
    exit 1
fi

DESTDIR=$1
if [[ ! -d $DESTDIR ]]; then
    echo "directory $DESTDIR doesn't exist." >&2
    exit 1
fi
shift

ALLREADABLE=true
for fidx in {1..$#}
do  
    if [[ ! -r $argv[$fidx] ]]; then
        echo "can't read file " $argv[$fidx] >&2
        ALLREADABLE=false
    fi
done

if [[ false == $ALLREADABLE ]]; then
    exit 1
fi

/usr/bin/inotifywait -e modify -m $argv | while read LINE
do
    FILENAME=`echo $LINE | /bin/sed "s/ MODIFY$//"`
    echo "copy $FILENAME to $DESTDIR" >&2
    /bin/cp "$FILENAME" "$DESTDIR"
done
5
5
3

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?