LoginSignup
5
6

More than 5 years have passed since last update.

シェルスクリプトで、あるファイルの更新日時が、ある特定の日時よりも新しいか調べる。

Posted at

入門UNIXシェルプログラミング の第8章に出てきた例なのですが、
日常の仕事で使えそうなのでメモしておきます。

touch -t ${DATETIME} /tmp/compared-file.$$

if [ -n "`find ${FILENAME} -newer /tmp/compared-file.$$ -print`" ]; then
  echo "Yes: ${FILENAME} is newer than ${DATETIME}." 
else
  echo "No: ${FILENAME} is not newer than ${DATETIME}." 

rm -f /tmp/compared-file.$$

上記で、
- FILENAME には対象のファイルパス
- DATETIMEには
      [[CC]YY]MMDDhhmm[.SS]
 形式の日時が入っているとする。('20160804194500'みたいな感じ)

3つのコマンド使いがポイント:
- touch コマンドを日時指定ありで使って比較対象の空のファイルを作る。
 (上記の例では、-t オプションを使っているが、-d でも可)
- find コマンドの -newer オプションを使って、調べたいファイルがこの空のファイルよりも新しいかどうかを、
- test コマンドの -n でfindが空ではない文字列を返すかどうかでチェックする。

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