17
19

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.

シェルスクリプトでファイルの更新日時がN時間前かチェックする

Posted at

stat を使う

stat でファイルの更新日時を取得して date の現在日時と比較する

[ $(( $(date +%s)0 - $(stat -c %Y FILE)0 )) -gt $((60 * 60 * 4)) ]

$(stat -c %Y FILE)0 の最後の 0 はファイルが存在しなかったとき用。

find を使う

find-mmin で更新日時で検索する。

[ "$(find FILE -mmin -$((60*4)) | wc -l)" -eq 0 ]

動作確認

上の2つを関数にする。

function f1()
{
  [ $(( $(date +%s)0 - $(stat -c %Y "$1")0 )) -gt $((60 * 60 * 4)) ]
}

function f2()
{
  [ "$(find "$1" -mmin -$((60*4)) | wc -l)" -eq 0 ]
}

確認のためのファイルを作成。

touch -d "now"     01.txt
touch -d "-6 hour" 02.txt

ll 01.txt 02.txt 
#=> -rw-r--r-- 1 ngyuki wheel 0 Oct 29 14:45 01.txt
#=> -rw-r--r-- 1 ngyuki wheel 0 Oct 29 08:45 02.txt

試してみる。

f1 01.txt && echo old || echo new
#=> new

f1 02.txt && echo old || echo new
#=> old

f1 03.txt && echo old || echo new
#=> stat: cannot stat ‘03.txt’: No such file or directory
#=> old

f2 01.txt && echo old || echo new
#=> new

f2 02.txt && echo old || echo new
#=> old

f2 03.txt && echo old || echo new
#=> find: ‘03.txt’: No such file or directory
#=> old
17
19
1

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
17
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?