Check two files are present on two different directories and pick latest

I have below two file of below patterns in two directories say NAS and FTP.

GE_REF_DATA*
GE_CUST_DET_DATA*

There can be files of the above pattern of previous dates as well.

I have to first check in the /NAS path if the file is present there. If yes, i need to pick the file names and store it in variable like below:

var1=`ls -t GE_REF_DATA* | head -n 1`
var2=`ls -t GE_CUST_DET_DATA* | head -n 1`

The file has to be of latest date.

If it’s not at NAS, i need to check at FTP path /FTP and do the exact same thing. There is a possibility that only one file exist at NAS/FTP.

I tried the below, but this is also not working. What is wrong in the below?

 cd /NAS
#var1=`ls -t GE_REF_DATA* | head -n 1`
#var2=`ls -t GE_CUST_DET_DATA* | head -n 1`

if [ -f /NAS/"GE_REF_DATA*".txt ] && [ -f /NAS/"GE_CUST_DET_DATA*".txt ]; then
var1=`ls -t GE_REF_DATA* | head -n 1`
var2=`ls -t GE_CUST_DET_DATA* | head -n 1`

echo "Files present at  NAS"
cd /FTP
elif [ -f /FTP/"GE_REF_DATA*".txt ] && [ -f /FTP/"GE_CUST_DET_DATA*".txt ]; then
var1=`ls -t GE_REF_DATA* | head -n 1`
var2=`ls -t GE_CUST_DET_DATA* | head -n 1`

echo "Files present at FTP"

echo $var1
echo $var2

else
echo "Files not present anywhere"

fi

Here is how to do it

FILE1 is newer (modification date) than FILE2

[ FILE1 -nt FILE2 ] && echo "yes" || echo "no"

Compare two file modification dates

file1="/NAS/foo.txt"
file2="/NAS/bar.txt"
if [ "$file1" -nt "$file2" ]
then
    echo "$file1 is newer than $file2"
fi

From the test man page:

  • FILE1 -ef FILE2 : FILE1 and FILE2 have the same device and inode numbers
  • FILE1 -nt FILE2 : FILE1 is newer (modification date) than FILE2
  • FILE1 -ot FILE2 : FILE1 is older than FILE2

Interesting problem and I didn’t know we could compare file like that.


Linux sysadmin blog - Linux/Unix Howtos and Tutorials - Linux bash shell scripting wiki