ファイルの日時を比較する方法 †
この記事は、2つファイルを比較し新しいか古いかの日時の比較を行うサンプルスクリプトになります。
使用したシェルはbashになります。
ファイルの日時比較のサンプルスクリプト
sample.sh †
本スクリプトは、1st.txt, 2nd.txtの2つのファイルを作成します。
2nd.txtファイルは1st.txtファイルが作成された後、3秒後に作成されます。(sleepコマンドを利用)
その後、ファイルの日時を比較します。
#!/bin/bash
echo "1st" > 1st.txt
echo "create 1st.txt"
echo "wait 3 sec..."
sleep 3
echo "2nd" > 2nd.txt
echo "create 2nd.txt"
ls --full-time 1st.txt 2nd.txt
if [ 2nd.txt -nt 1st.txt ]; then
echo "2nd.txt is newer than 1st.txt"
fi
if [ 1st.txt -ot 2nd.txt ]; then
echo "1st.txt is older than 2nd.txt"
fi
rm 1st.txt 2nd.txt
左辺のファイルが新しい場合 †
左辺のファイルの方が新しく右辺のファイルが古い場合の条件式は-ntになります。
(newer than とおぼえれば簡単です。)
上記サンプルスクリプトで該当する部分は以下の部分になります。
if [ 2nd.txt -nt 1st.txt ]; then
echo "2nd.txt is newer than 1st.txt"
fi
左辺ファイルが古い場合 †
左辺のファイルの方が古く右辺のファイルが新しい場合の条件式は-otになります。
(older than とおぼえれば簡単です。)
上記サンプルスクリプトで該当する部分は以下の部分になります。
if [ 1st.txt -ot 2nd.txt ]; then
echo "1st.txt is older than 2nd.txt"
fi
サンプルスクリプトの実行結果 †
以下、この記事のサンプルスクリプトを実行した時の出力です。
$ chmod +x sample.sh
$ ./sample.sh
create 1st.txt
wait 3 sec...
create 2nd.txt
-rw-rw-r-- 1 sakura sakura 4 2012-05-16 11:39:08.000000000 +0900 1st.txt
-rw-rw-r-- 1 sakura sakura 4 2012-05-16 11:39:11.000000000 +0900 2nd.txt
2nd.txt is newer than 1st.txt
1st.txt is older than 2nd.txt
まとめ †
-nt | 左辺ファイルが右辺ファイルより新しい場合は真 |
-ot | 左辺ファイルが右辺ファイルより古い場合は真 |
関連資料 †
逆引きシェルスクリプト/if文のサンプルシェルスクリプト・数値比較編
逆引きシェルスクリプト/if文のサンプル・ファイル・ディレクトリ編