Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

$? 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...