0

I'm getting unexpected results from the following

COMPARE(){
    if [ ! cmp $IPPATH/ip.old $IPPATH/ip.new >/dev/null 2>&1 ]; then
            echo compare going to create
            CREATE
    else
            echo same
    fi
}

I'm trying to compare the files, if they're the same, do nothing (i.e. display same, but if they're NOT the same then display compare going to create and then run the CREATE function.

However, I get the same "same" result when the file are identical and when they are definitely NOT the same.

these display correctly (as they should):

echo `cat $IPPATH/ip.old`
echo `cat $IPPATH/ip.new`
  • 3
    Possible duplicate of Confused about operators [[ vs [ vs ( vs (( . The [ operator accepts a restricted set of conditions, not full shell commands. Aside from that, your code is fine; just remove the [ and ] characters. – Mark Plotnick Sep 5 '16 at 16:50
  • Thanks, that did it. I don't know the difference between the operators, but now that I'm aware that there IS a difference, I'm going to be looking it up and learning so that I don't need to ask pointless questions in the future. Thanks! – Jim Sep 7 '16 at 7:11
7

The [ character in your if test means that you have told the shell to do the sort of evaluation documented in man test

It may not match exactly that man page because [ is builtin to most shells and ksh, bash, zsh etc may implement slightly different functionality.

One thing these don't do, though, is run an external command and test the results.

So we can do this another way

eg we can test to see if the output of the cmp command is non-blank:

if [ -n "$(cmp $IPPATH/ip.old $IPPATH/ip.new)" ]
then
  echo different
else
  echo same
fi

Or we can call cmp and test the return code, which is closer to your original intent, just without the [...] wrapping:

if ! cmp $IPPATH/ip.old $IPPATH/ip.new > /dev/null 2>&1
then
  echo different
else
  echo same
fi
| improve this answer | |

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.