Bash return values ($?)

Paul Smith paul at mad-scientist.net
Wed Oct 2 19:34:42 UTC 2013


On Wed, 2013-10-02 at 21:21 +0200, Johnny Rosenberg wrote:

> I am experimenting a little with C. I wrote a small application that
> returns an integer value. The value can be any integer value, even
> negative.

> However, when checking $? after running it, when my application
> returns -1, $? is 255. Is there a way to get around this? Some setting
> somewhere, perhaps?

No.

> Someone compiled and tested my application in Windows (I don't have
> Windows myself) and he said that e correct values (-1, for instance)
> was detected by the shell.

Yes, Windows supports negative exit codes.  UNIX does not.

> Seems like Bash chop the return value to 8 bits unsigned int. Is this
> a Bash thing or does this happen with the other shells (zsh, ksh, tcsh
> etc.) as well?

It has nothing to do with the shell, or any other user program.  The
UNIX standard interface, defined by POSIX, and implemented by every
UNIX-like kernel ever including the Linux kernel, restricts the exit
code of a process to an unsigned 8-bit integer.  Thus, exit codes are
always between 0 and 255 regardless of what value you return.

This is because on UNIX the entire final state of a process is encoded
into a single 32bit integer (and there are system call interfaces that
assume this).  In addition to the exit code, there are flags saying
whether the process dumped core, exited with a signal, etc. that must be
encoded into those 32 bits, so the exit code is restricted to 8 bits.






More information about the ubuntu-users mailing list