Compare file size and then copy/overwrite

// Redhat

I have this code working, but need to add one more qualification so that I don't overwrite the files.

#!/bin/sh
cd /P2/log/cerner_prod/millennium/archive/
for f in *
do      [ -f "$f" ] || continue     #If this isn't a regular file, skip it.
        [ -e "/P2/backup/$f" ] && continue  #If a backup already exists, skip it.
        cp "$f" /P2/backup/          # Make a backup copy.
done

What I like to do is:

1) compare the size of the same file (i.e. p2_000001.gz).
2) if the file size (p2_000001.gz) under /P2/backup/ is larger than that under /P2/log/cerner_prod/millennium/archive/, then skip it
3) if if the file size (p2_000001.gz) under /P2/backup/ is smaller than that under /P2/log/cerner_prod/millennium/archive/, then copy or overwrite

In this case, /P2/backup/ will have always the latest file.

Please advise. Appreciate your help!

It won't be the latest but the largest file.

Do you NEED to run that with sh ? Does your system have the stat (or equivalent) command?

---------- Post updated at 22:58 ---------- Previous update was at 22:49 ----------

With bash and stat :

 (( ($(stat -c"%s-" "$f" /P2/backup/"$f") 0)  > 0 )) && cp "$f" /P2/backup/

---------- Post updated at 23:03 ---------- Previous update was at 22:58 ----------

No bash required:

expr $(stat -c"%s >" "$f") $(stat -c"%s" /P2/backup/"$f") && cp "$f" /P2/backup/
3 Likes

Much appreciated!

 (( ($(stat -c"%s-" "$f" /P2/backup/"$f") 0)  > 0 )) && cp "$f" /P2/backup/

works absolutely charming.