user15350930
user15350930

Reputation: 65

Remove duplicate file using bash script

I have two files at path1 and path2 respectively. I want to delete file at path2 if content of both the files are same.

I tried to achieve this using

cmp -s path1 path2 rm path2 ||echo "files are different"

but it doesn't work. Why not?

Upvotes: 1

Views: 277

Answers (1)

John Kugelman
John Kugelman

Reputation: 361615

You're missing an &&.

cmp -s path1 path2 && rm path2 || echo "files are different"

I would use if/else rather than &&/|| here. If rm happens to fail the above code will incorrectly say "files are different". Using if/else avoids this hiccup.

if cmp -s path1 path2; then
    rm path2
else
    echo "files are different"
fi

(As a general rule, only use &&/|| if the command after && always succeeds. If there's any chance it could fail stick with an explicit if/else.)

Upvotes: 7

Related Questions