bitlvl
ES

Referencia de códigos de salida

Escribe un código para encontrarlo. Cualquier cosa por encima de 128 significa que el proceso fue matado por una señal: resta 128 para obtener el número de señal. La tabla está en inglés.

 
CódigoNombreSignificado
0SuccessThe command completed without error.
1General errorCatch-all: the program chose to signal failure (grep: no match; many tools: any error).
2Misuse of shell builtin / usage errorBash: wrong arguments to a builtin. grep: an error occurred (not just no match). Many CLIs: bad usage.
64EX_USAGECommand line usage error (sysexits.h).
65EX_DATAERRInput data was incorrect.
66EX_NOINPUTInput file did not exist or was unreadable.
67EX_NOUSERUser does not exist.
68EX_NOHOSTHost does not exist.
69EX_UNAVAILABLEService unavailable.
70EX_SOFTWAREInternal software error.
71EX_OSERROS error (fork failed, etc.).
72EX_OSFILECritical OS file missing.
73EX_CANTCREATCannot create output file.
74EX_IOERRInput/output error.
75EX_TEMPFAILTemporary failure; retry later (mail systems).
76EX_PROTOCOLRemote error in protocol.
77EX_NOPERMPermission denied.
78EX_CONFIGConfiguration error.
100Debian apt / dpkg errorapt-get: a package operation failed. Also Python: nothing standard.
125Docker: daemon errordocker run itself failed (bad option, image not found). Also xargs: command killed by signal / other failures.
126Command cannot executeFound but not executable (permission denied, or a directory). Also Docker: contained command cannot be invoked.
127Command not foundThe shell could not find the program on PATH (typo, missing package, wrong shebang).
128Invalid exit argumentexit called with a value outside 0–255.
129Killed by SIGHUP (128+1)Terminal hung up or daemon reload signal.
130Killed by SIGINT (128+2)Ctrl-C.
131Killed by SIGQUIT (128+3)Ctrl-\ (core dump).
132Killed by SIGILL (128+4)Illegal instruction: corrupted binary or wrong CPU architecture.
133Killed by SIGTRAP (128+5)Debugger breakpoint.
134Killed by SIGABRT (128+6)abort(): assertion failure, glibc detected heap corruption, Go/Rust panic in some modes.
135Killed by SIGBUS (128+7)Bus error: misaligned access or a memory-mapped file that was truncated.
136Killed by SIGFPE (128+8)Arithmetic error, typically integer division by zero.
137Killed by SIGKILL (128+9)Forcibly killed: OOM killer (check dmesg), kill -9, Docker/Kubernetes memory limit, timeout -s KILL.
139Killed by SIGSEGV (128+11)Segmentation fault: invalid memory access.
141Killed by SIGPIPE (128+13)Wrote to a closed pipe, e.g. `cmd | head` after head exited.
143Killed by SIGTERM (128+15)Polite termination request: kill, systemctl stop, docker stop (after the grace period it becomes 137).
148Killed by SIGTSTP (128+20)Ctrl-Z (stopped, reported by some shells).
152Killed by SIGXCPU (128+24)CPU time limit exceeded (ulimit -t).
153Killed by SIGXFSZ (128+25)File size limit exceeded (ulimit -f).
255Exit status out of range / -1exit(-1) wraps to 255. ssh: connection or protocol error. rsync: unexplained error.

Los resultados y mensajes de esta herramienta se muestran en inglés.

Cómo funcionan los códigos de salida

Todo proceso termina con un estado de 8 bits, de 0 a 255. Por convención 0 significa éxito y cualquier otro valor fallo; la shell lo expone como $?, y &&, ||, if y set -e bifurcan según él. El significado del número más allá de cero/no cero pertenece al programa, con unas pocas convenciones casi universales.

Los códigos propios de la shell

  • 126: el archivo se encontró pero no pudo ejecutarse. Falta el bit de ejecución, es un directorio, un binario de otra arquitectura o un montaje noexec.
  • 127: no encontrado. Una errata, un programa no instalado o un PATH distinto entre tu shell y el entorno en que se ejecuta el script (cron, systemd, Docker). También una línea shebang que apunta a un intérprete inexistente, incluidos finales de línea \r\n que producen /bin/bash\r.
  • 128 + n: el proceso murió por la señal n. La shell no puede devolver una señal directamente, así que suma 128. 130 es Ctrl-C (SIGINT 2), 137 es SIGKILL (9), 139 es SIGSEGV (11), 143 es SIGTERM (15). La referencia de señales las lista todas.

137 en contenedores

Un exit 137 de un contenedor es casi siempre el OOM killer del kernel o el runtime de contenedores aplicando un límite de memoria: al proceso se le envió SIGKILL, que no puede capturarse, así que la aplicación no registró nada. Comprueba docker inspect buscando OOMKilled: true, dmesg buscando «Out of memory», o los eventos de Kubernetes buscando OOMKilled. 143 es el resultado normal de docker stop o de la terminación de un pod cuando el proceso manejó SIGTERM; 137 tras un stop significa que no se cerró dentro del periodo de gracia.

sysexits.h

BSD definió los códigos 64–78 para que las herramientas de correo y de sistema informaran de categorías de fallo (EX_USAGE 64, EX_NOINPUT 66, EX_TEMPFAIL 75…). Postfix, sendmail y algunos programas en Perl y Go aún los usan; nada más lo hace, así que trátalos como una convención, no como una regla.

Preguntas

¿Qué significa el código de salida 1?

Un fallo genérico: el programa decidió que algo fue mal y no tenía un código más específico. Para grep significa que ninguna línea coincidió, que no es un error en absoluto. Lee la salida stderr del programa, no el número.

¿Por qué obtengo 127 en cron o systemd pero no en mi shell?

El PATH es distinto. El perfil de tu shell añade directorios como /usr/local/bin o ~/.local/bin que cron y systemd no ven. Usa rutas absolutas o fija PATH al principio del script.

¿Cuál es el código de salida máximo?

255. exit 256 da la vuelta a 0, exit 300 se convierte en 44 (300 mod 256). Los valores negativos también dan la vuelta: exit(-1) es 255.

¿Cómo obtengo el código de salida de una tubería?

Por defecto $? es el estado del último comando. set -o pipefail hace que la tubería falle si falla cualquier etapa, y el array PIPESTATUS de bash contiene el código de cada etapa.