Linux Shell Exit Code

if your program returns -1, the linux shell receives the exit code as an 8-bit unsigned integer (0255)

So what would be the value that Linux shell would receive if you return -1 from your application?

The kernel takes your int return value and maps it to 8 bits unsigned.

Negative numbers are converted using mod 256:

-1 mod 256 = 255

That’s why when you run:

./myprogram
echo $?

the echo will show 255 instead of -1 as you might have falsely expected.

Key takeaway

  • Linux exit codes are always unsigned 8-bit values (0–255).
  • Returning negative values in your program gets wrapped modulo 256.
  • Common convention:
    • 0 → success
    • Non-zero → error

Tip:

If you want to return an error code to the shell, always use 0–255 to avoid confusion. Returning -1 is technically allowed but becomes 255 in the shell.

Use 0 for success and 1–255 for errors to avoid confusion.

If you want a “standard” error code in Linux, just use 1 instead of -1

This is important to be aware of esp if you develop software using C# with mono or .net core where you might have a bash script that would automate task based on specific exit code from one of your linux C#/mono app.

Leave a Reply

Your email address will not be published. Required fields are marked *