error linux

Linux Exit Code 128 - Invalid Exit Argument

Understanding Linux exit code 128 - indicates an invalid argument was passed to the exit command, or serves as a base for signal-based exit codes.

What It Means

Exit code 128 has two meanings:

  1. Invalid exit argument: The exit command was called with an argument that is not a valid integer.
  2. Base for signal exit codes: When a process is terminated by a signal, the exit code is 128 + N, where N is the signal number. Exit code 128 itself means the signal number was 0, which is unusual.

The 128+N convention is crucial for understanding exit codes like 130 (SIGINT), 137 (SIGKILL), 139 (SIGSEGV), and 143 (SIGTERM).

Common Causes

  • Process was killed by a signal (exit codes 128+N)
  • Invalid argument passed to the exit built-in in a script
  • Using exit with a non-numeric or out-of-range argument
  • Container orchestration systems sending signals to processes

How to Fix

Understanding signal-based exit codes

# Common signal exit codes (128 + signal number)
# 128 + 1  = 129  (SIGHUP  - terminal hangup)
# 128 + 2  = 130  (SIGINT  - Ctrl+C)
# 128 + 9  = 137  (SIGKILL - force kill)
# 128 + 11 = 139  (SIGSEGV - segmentation fault)
# 128 + 15 = 143  (SIGTERM - graceful termination)

# Decode a signal exit code
exit_code=137
signal=$((exit_code - 128))
echo "Process killed by signal $signal"
kill -l $signal  # Output: KILL

Fix invalid exit arguments

# Wrong: non-numeric exit argument
exit "error"    # Results in exit code 128 or 2

# Wrong: exit code out of range (must be 0-255)
exit 999        # Wraps around: 999 % 256 = 231

# Right: use valid exit codes
exit 0   # Success
exit 1   # General error
exit 2   # Usage error

Handle signals in your scripts

#!/bin/bash

# Trap signals and handle gracefully
cleanup() {
  echo "Caught signal, cleaning up..."
  rm -f /tmp/lockfile
  exit 0
}

trap cleanup SIGINT SIGTERM  # Handle Ctrl+C and termination

# Long-running process
while true; do
  do_work
  sleep 1
done

Handle signals in Node.js

process.on('SIGTERM', () => {
  console.log('Received SIGTERM, shutting down gracefully...');
  server.close(() => {
    process.exit(0);
  });
});

process.on('SIGINT', () => {
  console.log('Received SIGINT, shutting down...');
  process.exit(0);
});

Check what signal killed a process

# After a command exits with 128+N
./my-program
status=$?

if [ $status -gt 128 ]; then
  signal=$((status - 128))
  echo "Process was killed by signal $signal ($(kill -l $signal))"
fi