Copy file only if newer

I only want the file copied if it is newer. But it still copies the file?

zip -u Ubuntu_Documents.zip ./*[.txt *.doc *.rtf *.html *.png *.pdf *.odt *.ods *.odg] 
cp -u Ubuntu_Documents.zip $DOCS_Backup/Ubuntu_Documents_`date +"%Y-%m-%d-%H-%M"`.zip

try:

[[ Ubuntu_Documents.zip -nt $DOCS_Backup/Ubuntu_Documents_`date +"%Y-%m-%d-%H-%M"`.zip ]] && cp Ubuntu_Documents.zip $DOCS_Backup/Ubuntu_Documents_`date +"%Y-%m-%d-%H-%M"`.zip

Not sure if shell used supports it. It was not specified.

1 Like

You need to be very fast to not copy your file - the -u, --update option, copies "only when the SOURCE file is newer than the destination file or when the destination file is missing". You'd need to copy twice within a minute to hit a file with the same name older than your actual one.

2 Likes

I use Bash as my shell.

Script is not working.

-rw-rw-r-- 1 andy andy 77896 Oct 9 22:15 Ubuntu_Scripts.zip

andy@7_/media/andy/MAXTOR_SDB1/Ubuntu_Mate_18.04/Script_Backups$ ls
Ubuntu_Scripts_2018-10-09-15-46.zip Ubuntu_Scripts_2018-10-09-22-15.zip
Ubuntu_Scripts_2018-10-09-20-00.zip Ubuntu_Scripts_2018-10-10-10-00.zip

Yes, the test utility operator -nt stands for newer than. If you check the man page for the test utility on your system or look for the term "conditional expression" on the man page for your shell, you'll find lots of useful tests that can be performed in your shell scripts. (Note that "conditional expression" might be all lowercase, all uppercase, or have the first letter of each word capitalized depending on which shell's man page you're reading.)

Most of the operators that are available with the [[ command (if your shell has a [[ command) are also available with the test utility invoked with:

test expression

or with:

[ expression ]

The test and [ utilities are available with all Bourne shell derived shells.

A solution to the problem mentioned in post#3 - a timestamp file.

last_bu=$DOCS_Backup/last_backup
if [[ ! -f $last_bu ] || [[ Ubuntu_Documents.zip -nt $last_bu ]]
then
  cp Ubuntu_Documents.zip $DOCS_Backup/Ubuntu_Documents_`date +"%Y-%m-%d-%H-%M"`.zip &&
  >$last_bu
fi