Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pipe command output, but keep the error code [duplicate]

Tags:

shell

unix

sh

How do I get the correct return code from a unix command line application after I've piped it through another command that succeeded?

In detail, here's the situation :

$ tar -cEvhf - -I ${sh_tar_inputlist} | gzip -5 -c > ${sh_tar_file}  --  when only the tar command fails $?=0
$ echo $?
0

And, what I'd like to see is:

$ tar -cEvhf - -I ${sh_tar_inputlist} 2>${sh_tar_error_file} | gzip -5 -c > ${sh_tar_file}
$ echo $?
1

Does anyone know how to accomplish this?

like image 375
SamiBOB Avatar asked Jan 12 '12 10:01

SamiBOB


People also ask

What command would you use to duplicate stdout from a program to both stdout and a file?

The tee command, used with a pipe, reads standard input, then writes the output of a program to standard output and simultaneously copies it into the specified file or files.

What does pipe command do?

Pipe is used to combine two or more commands, and in this, the output of one command acts as input to another command, and this command's output may act as input to the next command and so on. It can also be visualized as a temporary connection between two or more commands/ programs/ processes.

How do I redirect a script to a file in Linux?

In Linux, for redirecting output to a file, utilize the ”>” and ”>>” redirection operators or the top command. Redirection allows you to save or redirect the output of a command in another file on your system. You can use it to save the outputs and use them later for different purposes.


1 Answers

Use ${PIPESTATUS[0]} to get the exit status of the first command in the pipe.

For details, see http://tldp.org/LDP/abs/html/internalvariables.html#PIPESTATUSREF

See also http://cfajohnson.com/shell/cus-faq-2.html for other approaches if your shell does not support $PIPESTATUS.

like image 91
Shawn Chin Avatar answered Oct 20 '22 02:10

Shawn Chin