Problem with exit status

Hi,

Consider the output of the following commands:

case1)
-------
# ifconfig -a | grep "UP" | grep uplink0:1
# echo $?

Output is: 0

case2
------
# ifconfig -a | grep "UP" | grep uplink0:1; echo $?

Output is: 1

In case2 we got the exit code as 1, which is the actual exit code.
Why did we not get the actual exit code in case1?

What is the difference between executing two different command at the same time (as in case 2) and one after the other (as in case 1)? In both the cases the commands will get executed in the same sequence.

Any help will be highly appreciated.

Thanks.

Before starting off, you should know that the exit status that is printed is the exit status of the last command in the pipeline; i.e. the exit status of grep 'uplink0:1' is the one that is printed.

man grep says

       Normally, exit status is 0 if selected lines are found and 1 otherwise.
       But the exit status is 2 if an error occurred, unless the -q or --quiet
       or --silent option is used and a selected line is found.

So in your case, grep did find a favorable result and threw the exit status of 0. In the second case, grep threw up nothing. Hence an exit status of 1.

In case you do want to find out the exit status of the commands in the pipeline, look at this post - Pipelining.

vino