Sujay Davalgi
Sujay Davalgi

Reputation: 53

In shell-script, how to compare two files and know which one is latest?

I have two folders A & B. A is my working directory and B is my backup folder.

I compare files in the two folders and backup (From A to B) if there are any changes in A.

So, I used:

diffResult=( diff -q "${A/file-nmae}" "${B/file-name}" )

if [ -n "${diffResult}" ]; then

    <code to copy>
else

    <something else>
fi

The only problem is, in some cases, file in B is latest than A. So I dont want to backup in this case. How do I do it and how to check if which file is newer?

Upvotes: 2

Views: 625

Answers (2)

Lakshmanavaradhan
Lakshmanavaradhan

Reputation: 21

To find differents in b.txt

fgrep -v -f a.txt b.txt 

To find differents in a.txt

fgrep -v -f b.txt a.txt 

To find last modified ,last modified file at end

ls -lrt   

To find both changes and last modified use

fgrep -v -f a b && ls -lrt a b  | tail -1

Upvotes: 0

sjsam
sjsam

Reputation: 21965

The easiest way is to use the if primary expression -nt ie

if [ "A/fileX" -nt "B/fileX" ]
then
  mv A/fileX B/fileX
done

The [ documentation ] says :

[ FILE1 -nt FILE2 ] True if FILE1 has been changed more recently than FILE2, or if FILE1 exists and FILE2 does not.

Upvotes: 4

Related Questions