Bash: is missing file older than existing file?

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

3 Comments


  1. Good exercise in phylosophy. Do non existent objects belong to the (distant) past or to the future?

    Reply

    1. For practical purposes, past makes more sense, as main usage of this comparison is, I assume, updating dependencies: “if [ dest -ot src ]; then recreate dest from src; fi

      In this case, if dest does not exist, we also want to create it.

      Reply

Leave a Reply to Arkadi Klepatch Cancel reply

Your email address will not be published. Required fields are marked *