I have two directories named comp1 and comp2 and both have files named file1 and file2.

I need a bash script which read file1 from both the directories and take diff of each file and redirect to some other file. For example.

diff comp1/file1 comp2/file1 > file1.diff

  • 1
    diff -Nru comp1 comp2, oh and man diff
    – dawud
    Commented Jul 3, 2013 at 13:59

1 Answer 1


for f in comp1/* ; do
  diff "comp1/$f" "comp2/$f" > "$f.diff"

This script assumes you have files of the same name in both directories.

  • Thanks for the quick answer, that what I need. What if we need this recursively? for example further in comp1 directory there is another directory?
    – Toqeer
    Commented Jul 3, 2013 at 14:18
  • 1
    It depends on where you want to have the file with the output of diff. If you want it in one file, just use diff -Nru as proposed by @dawud. If you want separate files, just separate the output at '^---' with csplit.
    – Mathias Weidner
    Commented Jul 3, 2013 at 16:58
  • 1
    Don't iterate over the output of ls. Just use a glob. And quote your variables. Commented Jul 3, 2013 at 17:53
  • I have fixed the code in the answer.
    – user26112
    Commented Jul 4, 2013 at 4:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .