Bash: is missing file older than existing file?

May 24, 2020 00:12


Originally published at www.ikriv.com. Please leave any comments there.

In bash it is possible to test whether one file is older or newer than the other:

if [ file1 -nt file2 ]; then # do something fi if [ file3 -ot file4 ]; then # do something fi
However, the man page does not say what happens if one of the files does not exist. Experiment shows that at least on my systems (Ubuntu 16.04 and 18.04) non-existing files are consistently treated as created in the infinite past. I.e., any existing file is newer than non existing file, and any non existing file is older than any existing file. The results are summarized in the table below:

[ existing -nt missing ] ==> TRUE [ missing -nt existing ] ==> FALSE [ existing -ot missing ] ==> FALSE [ missing -ot existing ] ==> TRUE [ missing -nt missing ] ==> FALSE [ missing -ot missing ] ==> FALSE
BTW, here’s the script that prints this table:

#!/bin/bash function compare { echo -n "[ $1 $2 $3 ] ==> " if [ $1 $2 $3 ]; then echo TRUE; else echo FALSE; fi } touch existing compare existing -nt missing compare missing -nt existing compare existing -ot missing compare missing -ot existing compare missing -nt missing compare missing -ot missing

hacker's diary

Previous post Next post
Up