Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the exit status of the first command in a pipe? [duplicate]

I made a simple script:

$ more test.bash
#!/bin/bash
echo test
exit 1

When I run the script , the exit status should be 1

$ /tmp/test.bash
echo $?
1

But when I run this as the following

/tmp/test.bash | tr -d '\r' 1>>$LOG 2>>$LOG
echo $?
0

The exit status is 0, (not as expected 1)

It seems that the exit status comes from tr command. But I what I want is to get the exit status from the script - test.bash.

What do I need to add/change in my syntax in order to get the right exit status from the script, and not from the command after the pipe line?

like image 673
maihabunash Avatar asked Jul 14 '14 10:07

maihabunash


People also ask

How can you get the exit status of the command?

To display the exit code for the last command you ran on the command line, use the following command: $ echo $?

How do you exit a pipe pipe quote?

How to escape quotes and pipe? Capturing the output of the command (using backquotes) and then echo ing that is an antipattern. Just run the command directly, and let its output go to the usual place.

Which command is used to return the exit status of the command?

echo $? 2. It returns the exit status of the last executed command.

How do I display exit status in last command?

The echo command is used to display the exit code for the last executed Fault Management command.


1 Answers

Use the PIPESTATUS array:

$ ls foo | cat
ls: foo: No such file or directory
$ echo ${PIPESTATUS[0]} ${PIPESTATUS[1]}
2 0

Note: PIPESTATUS is a bashism (i.e. not POSIX).

like image 148
Jens Avatar answered Oct 26 '22 21:10

Jens