シェル - シェルスクリプト - ファイルのタイムスタンプ比較

クラウディア 
1. 概要
2. タイムスタンプを比較する

1. 概要

 表題の通り、ファイルのタイムスタンプを比較したかったのですよ。  本ページは、下記のサイトを参考にさせていただきました。
逆引きシェルスクリプト/ファイルの日時を比較する方法」
「【シェルスクリプト】条件分岐させるifの使い方!

2. タイムスタンプを比較する

 比較演算子は、「-nt」もしくは「-ot」であります。
 演算子    意味    備考 
-nt 「newer than」で、左辺が右辺よりも新しければ
-ot 「older then」で、左辺が右辺よりも古ければ

 では、同値という演算子は?
 ようわからんので、「else」を使います。
 下記のスクリプトを書いて。


#!/bin/sh

if [ a.txt -nt b.txt ]; then
  echo "a.txt is newer than b.txt"
elif [ a.txt -ot b.txt ]; then
  echo "a.txt is older than b.txt"
else
  echo "a.txt and b.txt have the same timestamp."
fi

ls -l *.txt
-rw-r--r-- 1 hogehoge hogehoge 8  3月  4 19:23 a.txt
-rw-r--r-- 1 hogehoge hogehoge 8  3月  4 19:32 b.txt
 という状況で実行すると、下記の結果が得られます。

a.txt is older than b.txt

ls -l *.txt
-rw-r--r-- 1 hogehoge hogehoge 8  3月  4 19:23 a.txt
-rw-r--r-- 1 hogehoge hogehoge 8  3月  4 19:32 b.txt
 という状況で実行すると、下記の結果が得られます。

a.txt is newer than b.txt

cp -p a.txt b.txt
 と、タイムスタンプが同じになるようにコピーして実行すると、下記の結果が得られます。

a.txt and b.txt have the same timestamp.
earthcar(アースカー)