2

I need help with comparing two files in makefile. I need something like this:

if [cmp $(FILE1) $(FILE2)] !=0; than 
 echo "OK" 
else 
 echo "WRONG" 
fi

But I am not sure how exactly to do that, Thanks

Libor Zapletal
  • 13,752
  • 20
  • 95
  • 182

2 Answers2

7

Edit: corrected mistaken use of -z to -eq 0 and added Makefile context help.

It's really a shell question, not specific to makefiles, but this code would work:

cmp -s $(FILE1) $(FILE2)
RETVAL=$?
if [ $RETVAL -eq 0 ]; then 
    echo "SAME" 
else 
    echo "NOT SAME" 
fi

In a makefile rule, that would look like:

my_compare:
    cmp -s $(FILE1) $(FILE2); \
    RETVAL=$$?; \
    if [ $$RETVAL -eq 0 ]; then \
            echo "SAME"; \
    else \
            echo "NOT SAME"; \
    fi
e.dan
  • 7,275
  • 1
  • 26
  • 29
  • I know it would be better in shell but I must do it in makefile. Your code compare files but then on RETVAL there is Error 1. – Libor Zapletal Apr 28 '11 at 05:43
  • You can do it in a makefile, sure - maybe your question was how to get the shell actions to execute correctly in a makefile rule - that wasn't so clear from the question. If so, see edit. Also note that I corrected the shell code - it had a mistake - oops, sorry. – e.dan Apr 28 '11 at 06:25
  • I am sorry if I didn´t say it clear but I needed it in a makefile rule. Now it works, thank you – Libor Zapletal Apr 28 '11 at 06:36
  • @Bibo - it was pretty clear actually - my bad :) glad it helped. – e.dan Apr 28 '11 at 06:58
  • 1
    Why don't you test `$?` (i.e., `$$?`) directly? I see no reason to store it in `RETVAL`. Better yet, just execute `cmp` in the `if`: `if cmp -s $(FILE1) $(FILE2); then ...` – Jack Kelly Apr 28 '11 at 09:45
  • 3
    @Jack - I agree with putting the `cmp` in the `if` itself - good point. But I have learned from experience to always save the exit status of shell commands in something named `RETVAL` since it avoids those tricky bugs when the next programmer comes along and puts other commands between, not realizing that the `if` was inextricably linked to the last command that was run. Putting it immediately in a variable makes this more obvious (I think) and makes it more maintainable. – e.dan Apr 28 '11 at 11:50
  • @e.dan re `RETVAL`: I guess that makes sense, but I'd store `RETVAL` on the same line as the command whose `$?` you are capturing. – Jack Kelly Apr 28 '11 at 22:38
2

Return code from diff command will be 0 if files are identical, and 1 if files differs.

Charles Brunet
  • 21,797
  • 24
  • 83
  • 124