Finding latest file in dir but getting syntax errors

I believe there are couple of syntax issues in my script, couldn't find them :frowning:
can someone help me with fixing it to make it work.

cd /abcde/
#get the latest filename excluding subdirs
filename=`ls -ltr | grep ^- | tail -1 | awk '{print $8}'`

#get system date and file timestamp and storing in variables
sysDate="$(date)"
fileDate="$(date -r $filename)"

#get day of sys and file dates
sysdateDay= `$(date +%d)`
filedateDay= `$(date -r $filename +%d)`

#get hour of sys and file dates
sysdateHour= `$(date +%H)`
filedateHour= `$(date -r $filename +%H)`

#find difference of days and hours in sys and file dates
daydiff= 'expr $day - $day2'
hourdiff= 'expr $hour - $hour2'

echo "Current date : $sysDate"
echo "File date    : $fileDate"

#checking if day is same but hour difference is more than 2 hrs
if [ $daydiff -eq "0" && $hourdiff -ge "2" ]
then
    echo "the newest file is more than 2 hours old...."

#checking if there is a day difference of 1 or more days
else if [ $daydiff -ge "1" ]
    echo  "the newest file is more than 24 hours old...."

#last file is less than 2 hours old
else
    echo "new files received within 2 hours"
fi

exit 0

consider a shorter bit of arithmetic:

# the the age of the file using epoch seconds
fileage=$(( $(date +%s) - $(date -r min.h.bak +%s) ))
# age expressed as hours:
echo "hours = $(( $fileage / 3600 ))"
# age in days:
echo "days = $(( $fileage / 86400 ))"

You errors have a space between the variable name and equal symbol in an assign statement

var ="bad"
var= "bad"
var = "bad"
# no spaces either side of the equals symbol.
var="correct"

You have a logic problem using %H for hours - file going over midnight i.e., yesterday at 2300 and today at 0106 will give you a negative number

1 Like

Can you send the error message?

Thanks

G

Does min.h.bak mean the filename in your suggestion ?