Educating yourself does not mean that you were stupid in the first place; it means that you are intelligent enough to know that there is plenty left to 'learn'. -Melanie Joy

Thursday, 4 October 2012

PIPESTATUS and its Alternative

October 04, 2012 Posted by Dinesh , , No comments
$> cat /etc/hosts | grep 000.000
$> $?
1


$> cat /etc/hosts | grep 000.000 | uniq
$> $?
0

Why is it returning success (0) though it fails during grep ??
the return code of a pipeline will be that of the return status of the rightmost command .
How to resolve this ??
use inbuilt PIPESTATUS variable.

PIPESTATUS is a array variable which contain the exit status of each command in piped commands. 

$> cat /etc/hosts | grep 000.000 | uniq
$> echo ${PIPESTATUS[*]}
0 1 0

here $PIPESTATUS[0] contains the exit status of cat /etc/hosts command
$PIPESTATUS[1] contains the exit status of grep 000.000
$PIPESTATUS[2] contains the exit status of uniq


The other way around for this is setting pipefail.

$> set -o pipefail
$> cat /etc/hosts | grep 000.000 | uniq
$> $?
1


0 comments:

Post a Comment