ablog

不器用で落着きのない技術者のメモ

bash でファイルのタイムスタンプを比較するロジック

  • compare.sh
#!/bin/bash

# a and b don't exist
if [[ ! -f a && ! -f b ]];then
        echo a and b don\'t exist
# b doesn't exist
elif [[ -f a && ! -f b ]];then
        echo b doesn\'t exist
# a doesn't exist
elif [[ ! -f a && -f b ]];then
        echo a doesn\'t exist
# a and b exist
elif [[ -f a && -f b ]];then
        # mtime of a and b equals
        if [[ ! a -nt b && ! a -ot b ]];then
                echo mtime of a and b equals
        # a is older than b
        elif [ a -ot b ];then
                echo a older than b
        # a is newer than b
        else
                echo a newer than b
        fi
fi
  • test_compare.sh
#!/bin/bash

rm a b > /dev/null 2>&1
./compare.sh

touch a
./compare.sh

rm a
touch b
./compare.sh

touch a
cp -p a b
./compare.sh

touch a
sleep 1
touch b
./compare.sh

touch b
sleep 1
touch a
./compare.sh
  • テスト結果
$ ./test_compare.sh 
a and b don't exist
b doesn't exist
a doesn't exist
mtime of a and b equals
a older than b
a newer than b