I'm looking for a simple way to have an if
statement where the conditional is whether the 2 newest files in a given directory (recursively) are identical in contents.
1 Answer
One way of making the comparison for files contained within a directory in bash without parsing ls
is:
unset -v penultimate ## one before newest
unset -v latest ## newest
for file in "$dirname"/*; do
[[ $file -nt $latest ]] && penultimate="$latest" && latest="$file"
done
if [[ -f $latest ]] && [[ -f $penultimate ]]; then
if diff -q "$penultimate" "$latest" ; then
printf "Files '%s' and '%s' are identical\n" "$penultimate" "$latest"
fi
fi
Note: if the files differ, the default behavior of diff -q
will output: Files '%s' and '%s' differ\n" "$penultimate" "$latest"
. Also note, the above compares for the existence of 2 files and not whether either of the newest two are symbolic links. It further does not compare the contents of subdirectories for the given directory.
diff
,cmp
, etc.). (1) as far as I know is not so easy. There'sls -t
, but parsingls
output is always frowned upon; then there'sstat
, but you might need to manually sort the timestamps.readarray -t files < <(ls -t /your/dir/ | head -2); if diff -q "${files[@]}"; then echo identical; fi
. If you are certain that the file names can never contain spaces, you can do the simplerfiles=$(ls -t /your/dir/ | head -2); if diff -q $files; then echo identical; fi
. But one day, there will be a space in a file name...