5

I have a val.py python script that returns a negative number.

import sys
sys.exit(-1234)

When I run this bash script, I get the value $? as return value of 46 (not -1234). Even when I tried to compare the value with $? == 46 or $? == "46", it doesn't work at all.

python val.py
echo $?

if [ $? == 46 ]; then
    echo "Match"
else
    echo "NO"
fi
  • Q1 : Why the return value is not correctly stored in $??
  • Q2 : Why the $? == NUMBER comparison doesn't work?

1 Answer 1

11

The status passed to exit() by a process is masked to a single byte, so it's limited to the range [0-255]. See the exit documentation:

The value of status may be 0, EXIT_SUCCESS, EXIT_FAILURE, or any other value, though only the least significant 8 bits (that is, status & 0377) shall be available to a waiting parent process.

On two's complement implementations, -1234d == 0x...ffffb2e, and 0x2e == 46d, so the result you are seeing is expected.

For you second question, you if statement is testing the exit status from echo $?, not the one from your python program.

Try:

python val.py
rc=$?
echo $rc
if [ $rc == 46 ] ; then
...
4
  • 1
    I would add that $((-1234 & 255)) gives exactly 46.
    – enzotib
    Commented Oct 2, 2011 at 19:42
  • Good point, added an piece about that.
    – Mat
    Commented Oct 2, 2011 at 19:47
  • 0377 is quite a strange way to write 255 or 0xff! Commented Oct 2, 2011 at 20:02
  • 1
    Sometimes known as the "not a tty problem", because in the old days people would print out the errno, and then use the C function strerror that printed out what the error code meant, only to find it always said "not a tty", because printf set errno itself to that value. Commented Oct 3, 2011 at 2:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .