Analyzing Diff Results in a Script Shell

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

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 not contain anything, and the above test will be evaluated as true.

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

On the line if [....].

Any ideas?

+4
source share
5 answers

Do you care about what the actual differences are, or just different files? If this is the last, you do not need to parse the output; you can check the exit code.

 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 
+15
source

The option is provided for this: -q (or --quiet ). It tells diff to simply give the exit code to indicate whether the files were the same. So you can do this:

 if diff -q "$dest_file" "$source_file"; then # files are identical else # files differ fi 

or if you want to change two sentences:

 if ! diff -q "$dest_file" "$source_file"; then # files differ else # files are identical fi 

If you really wanted to do it your own way (that is, you need a way out), you should do this:

 if [ -n "$diff_output" -o ... ]; then ... fi 

-n means "check if the next line is non-empty. You must also surround it with quotation marks, so if it is empty, the test still has a line - you get your error because your test evaluates to some_other_condition -o -o some_other_condition2 that, as you can see, will not work.

+1
source

diff is designed to compare files line by line to handle the difference tool, for example patch . If you just want to check if they are different, you should use cmp :

 cmp --quiet $source_file $dest_file || echo Different 
+1
source
 diff $FILE $FILE2 if [ $? = 0 ]; then echo "TWO FILES ARE SAME" else echo "TWO FILES ARE SOMEWHAT DIFFERENT" fi 
+1
source

Check files for difference in bash

 source_file=abc.txt dest_file=xyz.txt if [[ -z $(sdiff -s $dest_file $source_file) ]]; then echo "Files are same" else echo "Files are different" fi 

Code tested on RHEL/CentOS Linux (6.X and 7.X)

0
source

Source: https://habr.com/ru/post/1307394/


All Articles