Home > Software engineering >  Linux Bash, Test command, why [ 0 -ne 0 ] is false instead of true?
Linux Bash, Test command, why [ 0 -ne 0 ] is false instead of true?

Time:05-04

When using test command in Linux Bash and numeric comparison between "Zero" equal to "zero" fetches an exit code 0 through echo $?

$[ 0 -eq 0 ]
$echo $?
0

However, when testing the same with an NOT EQUAL, why my exit code shows false and exit with value 1?

$[ 0 -ne 0 ]
$echo $?
1

man Test

INTEGER1 -ne INTEGER2
          INTEGER1 is not equal to INTEGER2

Could someone explain the logic behind the not equal to when equating with a same integer?

CodePudding user response:

In bash, 0 (which really means no error) means true, non-zero (such as 1) means there was some error, AKA false.

Try this:

if [ 0 -ne 0 ]
then
  echo The above is not true
else
  echo The above is true
fi

Or, in one-liner form:

if [ 0 -ne 0 ]; then echo true; else echo false; fi

CodePudding user response:

Convention is that an exit code of zero means success and non-zero means error/failure. Consider:

$ true
$ echo $?
0
$ false
$ echo $?
1
$ if true; then echo ok; else echo no; fi
ok
$ if false; then echo ok; else echo no; fi
no
$ if [ 0 -ne 0 ]; then echo ok; else echo no; fi
no
  • Related