How Do I Compare Two Files with a Shell Script?

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 :

Hi!
1234
5678
1111
hello

file2:

1111
5678
1234
Hi!
hello

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.

5 Answers

In bash:

diff --brief <(sort file1) <(sort file2)
4

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
comp_value=$?

if [ $comp_value -eq 1 ]
then
    echo "do something because they're different"
else
    echo "do something because they're identical"
fi
1

Should also work :

comm -3 file1 file2

I think this is enough characters for an answer...

Whilst diff is a perfectly fine answer, I'd probably use cmp instead which is specifically for doing a byte by byte comparison of two files.

Because of this, it has the added bonus of being able to compare binary files.

if cmp -s "file1" "file2"
then
   echo "The files match"
else
   echo "The files are different"
fi

I'm led to believe it's faster than using diff although I've not personally tested that.

3

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

#!/bin/bash

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest