Skip to content

Instantly share code, notes, and snippets.

@hgwr
Created July 10, 2019 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hgwr/56abb64a01a29a22307bd8a2ca3cd15c to your computer and use it in GitHub Desktop.
Save hgwr/56abb64a01a29a22307bd8a2ca3cd15c to your computer and use it in GitHub Desktop.
Watching files and directories bash script
#!/bin/bash -eu
#
# import from https://qiita.com/sonodar/items/ddeeb98525ef4c03d48e
#
# Requirement: yum install -y inotify-tools
#
# Usage: ./watch-file.sh /home/ads_hagiwara/tmp/tmp '^.*\.csv$' echo
#
trap "exit 0" 3 # QUITシグナルで停止
WATCH_DIR=$1 # 監視するディレクトリ
FILE_PATTERN=$2 # ファイル名正規表現
COMMAND=$3 # ファイル更新時に実行するコマンド
# --formatで"ディレクトリ ファイル名 イベント"の形式で出力するように指定
inotifywait -e CLOSE_WRITE -m -r ${WATCH_DIR} --format "%w %f %e" | \
while read LINE; do
# --format指定した通りに変数に格納
declare -a eventData=(${LINE})
dirPath=${eventData[0]}
fileName=${eventData[1]}
# ファイル名パターンマッチング (マッチしなかったら無視)
[[ $fileName =~ ${FILE_PATTERN} ]] || continue
${COMMAND} "${dirPath}${fileName}"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment