Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Given two files, I want to write a shell script that reads each line from file1 and checks if it is there in file2. If a line is not found it should output two files are different and exit. The files can contain words numbers or anything. For example :

file1 :




In this case two files should be equal. if file2 has "hello!!!" instead of "hello" then the files are different. I'm using bash script. How can I do this. It is not important that I need to do it in a nested loop but that's what I thought is the only way. Thanks for your help.

share|improve this question
up vote 8 down vote accepted

In bash:

diff --brief <(sort file1) <(sort file2)
share|improve this answer
What if the file is a csv file. would sorting still work ? – Sunil Jan 18 '11 at 17:36
sort doesn't care about the exact contents unless you tell it to. – Ignacio Vazquez-Abrams Jan 18 '11 at 17:37
Thank you very much. – Sunil Jan 18 '11 at 17:42
Is it possible to find which lines differ ? – Sunil Jan 19 '11 at 2:07
Remove --brief and add format options, e.g. -u. – Ignacio Vazquez-Abrams Jan 19 '11 at 2:07

diff sets its exit status to indicate if the files are the same or not. The exit status is accessible in the special variable $?. You can expand on Ignacio's answer this way:

diff --brief <(sort file1) <(sort file2) >/dev/null

if [ $comp_value -eq 1 ]
    echo "do something because they're different"
    echo "do something because they're identical"
share|improve this answer
This was useful. Thanks – Sunil Jan 18 '11 at 18:55
You can just do if diff ... >/dev/null without the brackets and variable. – Dennis Williamson Jan 18 '11 at 20:34

comm -3 file1 file2

should also work. I think this is enough characters for an answer...

share|improve this answer

Adding this because I think the [[ ]] && || construct is pretty neat:


[[ `diff ${HOME}/file1 ${HOME}/file2` ]] &&  
   (echo "files different") ||
   (echo "files same")
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.