3

How can I check if a file is newer that the target file?

In a shell script, intended to run on a Mac, I want to do something like this:

#!/bin/bash
if [ $SourceFile dateisgreater $TargetFile ] then
    echo "SourceFile is newer that Targetfile"
fi
4
#/bin/bash
if [ "$SourceFile" -nt "$TargetFile" ]; then
    echo "SourceFile is newer than Targetfile"
fi

-nt means "newer than".

I've added quotes around the file names because if you need quotes on the echo, tehn you also need quotes on the file names...

1
  • Quoting around the variables is in case the values (the names of the files in this case) have white space. Without quoting and with white space, bash would not be able to parse the if test correctly.
    – suspectus
    Mar 17 '15 at 12:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.