1

I've seen numerous answers to questions here and elsewhere that say you can do a grep search of a variable by echoing the variable and piping that to grep. Following the syntax of these examples, however, isn't working for me.

The following code fails, echoing "found" every time, no matter what string I'm searching for with grep. What am I doing wrong?

TEST='This is a test of the emergency broadcast system.'
echo $TEST | grep 'blah'
if [ $? -eq 0 ]
then
    echo 'not found'
else
    echo 'found'
fi
fedorqui
  • 275,237
  • 103
  • 548
  • 598
T. Reed
  • 181
  • 1
  • 9

2 Answers2

9

Your check should be the other way round.

From man grep:

EXIT STATUS
       The  exit  status is 0 if selected lines are found, and 1 if not found.
       If an error occurred the exit status is 2.  (Note: POSIX error handling
       code should check for '2' or greater.)

See an example:

$ echo "hello" | grep h
hello
$ echo $?
0
$ echo "hello" | grep t
$ echo $?
1

However, it is best to use Bash tools for this:

[[ $TEST =~ *blah* ]] && echo "found" || echo "not found"
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
1

Zero means true in shell scripting. You can even simplify it like so:

TEST='This is a test of the emergency broadcast system.'
if echo "$TEST" | grep 'blah'
then
    echo 'found'
else
    echo 'not found'
fi
Karel Vlk
  • 230
  • 1
  • 6
  • 3
    It does *not* mean true; it means *success*. – chepner May 10 '16 at 13:23
  • I don't think the two statements are mutually exclusive. – Karel Vlk May 10 '16 at 13:47
  • _if_ interprets exit statuses as boolean values with 0 evaluating to _true_ and anything else to _false_. – Karel Vlk May 10 '16 at 13:53
  • Therefore "Zero means true to an `if` statement". – trojanfoe May 10 '16 at 13:56
  • No, zero does not mean true anywhere. Zero is a success exit status from a command and `if command` tests the exit status of `command`. It's like in C if you wrote `if ( cmd() == 0 ) {do success stuff}`. That statement wouldn't mean that zero means true either. It is 100% wrong to say that zero means true. – Ed Morton May 10 '16 at 18:00