If statement giving "else" response to both cmp results

5,596

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
Share:
5,596

Related videos on Youtube

Jim
Author by

Jim

Updated on September 18, 2022

Comments

  • Jim
    Jim almost 2 years

    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`
    
    • Mark Plotnick
      Mark Plotnick almost 8 years
      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.
    • Jim
      Jim almost 8 years
      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!