0
[ $var -eq $val ]

What will be the value of $? after the above condition/test if it fails? Can I assume that it will always be 1?

Edit: After reading answers I realized my question wasn't precise. I meant "will it be always 1 if no error occurs?".

NPS
  • 6,003
  • 11
  • 53
  • 90

2 Answers2

2

No. it wont be always 1, if condition fails.

for eg:

[root@localhost ~]# [ xxxxxx15 -gt "$10" ]
bash: [: xxxxxx15: integer expression expected
[root@localhost ~]# echo $?
2

exit status may vary based on operator/conditions you have applied

DevD
  • 664
  • 5
  • 16
2

Yes, at least as long as an error doesn't occur (so technically "no" in the general case, I guess?). See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html#tag_20_128_14:

The following exit values shall be returned:

  • 0

    expression evaluated to true.

  • 1

    expression evaluated to false or expression was missing.

  • >1

    An error occurred.

Or https://www.gnu.org/software/bash/manual/bashref.html#Bourne-Shell-Builtins:

Evaluate a conditional expression expr and return a status of 0 (true) or 1 (false).

melpomene
  • 84,125
  • 8
  • 85
  • 148