Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?
share|improve this question
add comment

1 Answer

up vote 12 down vote accepted

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
...
share|improve this answer
1  
I would add that $((-1234 & 255)) gives exactly 46. –  enzotib Oct 2 '11 at 19:42
    
Good point, added an piece about that. –  Mat Oct 2 '11 at 19:47
    
0377 is quite a strange way to write 255 or 0xff! –  Stéphane Gimenez Oct 2 '11 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. –  Paul Tomblin Oct 3 '11 at 2:44
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.