1

Code

a.py

import sys
import errno


def main():
    try:
        raise Exception("asdf")
        sys.stdout.write('{"v1": "kk"}')
        sys.stdout.flush()
    except IOError as e:
        # This catching exception is for preventing 'Broken Pipe' error
        # ref: https://www.geeksforgeeks.org/broken-pipe-error-in-python/
        if e.errno == errno.EPIPE:
          pass 

if __name__ == "__main__":
    main()

b.py

import io
import sys


def main():
    # Getting input from the previous process's std output
    input_messages = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
    for message in input_messages:
        print(message)


if __name__ == '__main__':
    main()

1. Experiment 1

1.1 a.sh

echo $?   # print 'exit code'
python a.py   
echo $?

1.2 Execution result

$ sh a.sh
>> 
0
Traceback (most recent call last):
  File "/Users/chois/Dropbox/Programming/Workspace/chois_workflow/data_ingestor/a.py", line 67, in <module>
    main()
  File "/Users/chois/Dropbox/Programming/Workspace/chois_workflow/data_ingestor/a.py", line 57, in main
    raise Exception("asdf")
Exception: asdf
1

--> Exit code is 1 due to the exception

2. Experiment 2

2.1 a.sh

echo $?   # print 'exit code'
python a.py | python b.py
echo $?

2.2 Execution result

$ sh a.sh
>> 
0
Traceback (most recent call last):
  File "a.py", line 67, in <module>
    main()
  File "a.py", line 57, in main
    raise Exception("asdf")
Exception: asdf
0

--> Exit code is still 0, even process has an error.

How can I make the command with pipe have exit code of 1?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
user3595632
  • 5,380
  • 10
  • 55
  • 111
  • 1
    Or this? [Get exit status of process that's piped to another](https://unix.stackexchange.com/q/14270/217726) – Joseph Sible-Reinstate Monica May 25 '22 at 02:39
  • 1
    tl;dr of dupes: `set -o pipefail` – Joseph Sible-Reinstate Monica May 25 '22 at 02:40
  • 1
    I removed the `python` tag from this question because Python doesn't have anything to do with the problem and Python experts have no particular advantage in answering the question. Here, Python is only being used to create a process that exits with an error code; the question is about how the shell deals with exit status of the components of a pipeline. – Karl Knechtel May 25 '22 at 02:53

0 Answers0