Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why exit code 141 with grep -q?

Can someone explain why I get exit code 141 from the below?

#!/usr/bin/bash  set -o pipefail  zfs list | grep tank echo a ${PIPESTATUS[@]}  zfs list | grep -q tank echo b ${PIPESTATUS[@]}  cat /etc/passwd | grep -q root echo c ${PIPESTATUS[@]} 

I get

... a 0 0 b 141 0 c 0 0 

From my understanding exit code 141 is a failure, but the line above gives zero, so it should be success, I would say.

like image 429
Sandra Schlichting Avatar asked Oct 01 '13 15:10

Sandra Schlichting


People also ask

What is exit code in shell script?

Exit Codes. Exit codes are a number between 0 and 255, which is returned by any Unix command when it returns control to its parent process. Other numbers can be used, but these are treated modulo 256, so exit -10 is equivalent to exit 246 , and exit 257 is equivalent to exit 1 .

What is exit code in Linux?

What is an exit code in the UNIX or Linux shell? An exit code, or sometimes known as a return code, is the code returned to a parent process by an executable. On POSIX systems the standard exit code is 0 for success and any number from 1 to 255 for anything else.

What do exit codes mean?

An exit code or exit status is a number that is returned by an executable to show whether it was successful. This is also sometimes called a return code, or in some cases, an error code, although the terminology here may be slightly different.

Why is it important to use exit codes in Linux?

More Linux resources When you execute a command or run a script, you receive an exit code. An exit code is a system response that reports success, an error, or another condition that provides a clue about what caused an unexpected result from your command or script.


1 Answers

This is because grep -q exits immediately with a zero status as soon as a match is found. The zfs command is still writing to the pipe, but there is no reader (because grep has exited), so it is sent a SIGPIPE signal from the kernel and it exits with a status of 141.

Another common place where you see this behaviour is with head. e.g.

$ seq 1 10000 | head -1 1  $ echo ${PIPESTATUS[@]} 141 0 

In this case, head read the first line and terminated which generated a SIGPIPE signal and seq exited with 141.

See "The Infamous SIGPIPE Signal" from The Linux Programmer's Guide.

like image 93
dogbane Avatar answered Oct 09 '22 03:10

dogbane