2
2

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.

あるファイルが前回チェックした時から更新されているかを判断する小技

Last updated at Posted at 2016-01-14

bash のファイル比較演算子を使って一時ファイルと日付を比較すると楽です。

is_update 関数を作成する

試しにやってみましょう。

is_update_func.sh
function is_update
{
  TMPFILE=".${1}.ts"

  if [ "${1}" -nt "${TMPFILE}" ]
  then
    touch ${TMPFILE}
    echo "更新されたね"
    return 0
  else
    return 1
  fi
}

さて、こんな関数定義ファイルを作ってだ。

. is_update_func.sh

sourceします。

使い方

$ touch myfile
$ is_update myfile
更新されたね
$ is_update myfile
$ is_update myfile
$ touch myfile
$ is_update myfile
更新されたね
$ is_update myfile
$

ファイルが更新されたら「更新されたね」と出力されています。

解説

別に解説するまでもないんだけど、bash の -nt ファイル比較演算子は左辺のファイルの方が新しいと真を返す。

右辺のファイルがない時も真を返す。

       file1 -nt file2
              True if file1 is newer (according to modification date) than file2, or if file1 exists and file2 does not.

というわけで、こういう用途にはぴったりなのです。

なるべく別プロセスを起動したくないとか言って touch でやらずに :>${TMPFILE} するケースもあると思うけど、自分はあんまり気にしない…。意図がわかりづらいし。

余談

このくらいにしてもいいか。ワンライナー風味。戻り値 0 なら更新されている。0 以外だと更新されていない。

function is_update(){
  test "${1}" -nt ".${1}.ts"  && :>".${1}.ts"
}
2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?