Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing result of Diff in Shell Script

Tags:

linux

bash

shell

I want to compare two files and see if they are the same or not in my shell script, my way is:

diff_output=`diff ${dest_file} ${source_file}`

if [ some_other_condition -o ${diff_output} -o some_other_condition2 ]
then
....
fi

Basically, if they are the same ${diff_output} should contain nothing and the above test would evaluate to true.

But when I run my script, it says
[: too many arguments

On the if [....] line.

Any ideas?

like image 383
Saobi Avatar asked Dec 01 '22 05:12

Saobi


1 Answers

Do you care about what the actual differences are, or just whether the files are different? If it's the latter you don't need to parse the output; you can check the exit code instead.

if diff -q "$source_file" "$dest_file" > /dev/null; then
    : # files are the same
else
    : # files are different
fi

Or use cmp which is more efficient:

if cmp -s "$source_file" "$dest_file"; then
    : # files are the same
else
    : # files are different
fi
like image 56
John Kugelman Avatar answered Dec 04 '22 03:12

John Kugelman