Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

bash - Checking status of a command in a pipeline

I want to grep for a string and cut a field if there is a match. Problem is that, no matter if there is a match or not, the output of the command $? is 0 which is weird. Please see the output below:

$ R=`grep g09 tor1.sh | cut -d ' ' -f2`
$ echo $R
test
$ R=`grep g09 tor1.sh | cut -d ' ' -f2`
$ echo $?
0

As you can see, there is a match but $? is 0. Now see this:

$ R=`grep g09 tor.sh | cut -d ' ' -f2`
$ echo $R

$ R=`grep g09 tor.sh | cut -d ' ' -f2`
$ echo $?
0

Here, there is no match for g09 but $? is still 0. Why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

$? is the overall or final exit status. What you need to look at is a bash array named:

PIPESTATUS

That gives you status of individual piped command.

So for you case:

read str < <(grep g09 tor.sh | cut -d ' ' -f2`)

echo ${PIPESTATUS[0]}
1

Here 1 means failure of first grep command in pipeline.

PS: Please note that we're using process substitution, instead of command substitution to be able to set PIPESTATUS correctly in current shell.

Example:

read str < <(grep 'bar' <<< 'foo bar baz' | cut -d ' ' -f2)
echo ${PIPESTATUS[0]}
0

read str < <(grep 'cat' <<< 'foo bar baz' | cut -d ' ' -f2)
echo ${PIPESTATUS[0]}
1

In the first example grep runs successfully hence we get ${PIPESTATUS[0]} as 0 but 1 in 2nd example when grep fails to find anything.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...