0

I would like to compare 2 files using diff and then if it returns nothing then echo "no diff" else display the difference. My current if statement only works if there is no difference but if there is then it gives me a "not found" error.

This is what the test.sh looks like:

#!/bin/zsh
if [$(diff file1 file2) = '']
then
    echo "no diff"
else
    diff file1 file2
fi

If files are same:

$ sh test.sh
no diff

If files are different:

$ cat file1
hello

$ cat file2
goodbye

$ sh test.sh
test.sh: 1: test.sh: [1,8c1,8: not found
< hello
---
> goodbye

In my search to find solutions, I found that having spaces if [ $(diff vs if [$(diff made a difference and using a single = vs == also helped. I figured the problem must be that I'm testing the output for '' (nothing). It actually does work but the "not found" line doesn't belong there. I don't just want to silence that annoying line but do the if statement the proper way because there should be a way to get the result I need without having to run the diff twice.

3

diff provides an exit status of zero if no differences were found, so just use diff once and output message if required:

if diff file1 file2; then
    echo 'no diff'
fi

  • diff utility may have the option -s/--report-identical-files (an extension to the POSIX specification). This would simplify the command to:

    diff -s file1 file2
    
  • Reason for error [1,8c1,8: not found was bad syntax: [ needs to appear on its own with a valid expression, and a closing ] argument. Info about how to use test can be found here on unix.stackexchange (link link link) & in manual pages man 1 test & man 1p test

  • In test.sh, the first line is #!/bin/zsh, but then the script is being run with sh interpreter (which probably isn't zsh). If you do want to use zsh features, then you'll want to make sure that you are actually running the script with zsh
1
  • Yes, that gives me a better result! I'm still getting 1,8c1,8 as part of the output. How can I get rid of that? EDIT: Wait, I see that's from diff itself and the -s option is actually what I needed. Thanks.
    – ntruter42
    May 24 '20 at 3:13

Your Answer

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

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