Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep return 0 if no match

Tags:

grep

return

match

Is there any bash script which can return me a result=true with command grep?

Example: There are 1000 records of 103.12.88 in my CF logs. Can I do a grep 103.12.88 if detect 1 or more results then print/output result show me either YES or True

like image 609
julian lee Avatar asked Sep 04 '19 12:09

julian lee


People also ask

What does grep return if no match?

Indeed, grep returns 0 if it matches, and non-zero if it does not.

Does grep return null?

If the pattern isn't found in the file, grep returns false (i.e. exits with a non-zero exit code), so the echo is executed. The -e says to interpret escapes, so the echo will print the current path, an ASCII nul , and the literal NULL .

Does grep return a string?

The grep command searches a text file based on a series of options and search string and returns the lines of the text file which contain the matching search string.

How check grep exit status?

Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent option is used and a line is selected, the exit status is 0 even if an error occurred. Other grep implementations may exit with status greater than 2 on error.


3 Answers

The actual answer to this question is to add || true to the end of the command, e.g.:

echo thing | grep x || true

This will still output a 0 return code.

like image 112
sebcoe Avatar answered Oct 13 '22 12:10

sebcoe


You are processing the return value incorrectly.

value=$( grep -ic "210.64.203" /var/logs )

sets value to the output of the grep, not to its return code.

After executing a command the exit code it stored in $?, but you usually don't need it.

if grep -ic "210.64.203" /var/logs 
then echo "Found..."
else echo "not found"
fi

If you want the value, then test for content.

rec="$( grep -ic "210.64.203" /var/logs )"
if [ -n "$rec" ] ; then echo found; fi

Or if using bash,

if [[ "$rec" ]] ; then echo found; fi

though I prefer to be explicit -

if [[ -n "$rec" ]] ; then echo found; fi
like image 2
Paul Hodges Avatar answered Oct 13 '22 12:10

Paul Hodges


[user@host ~]$ cat ~/mylogfile.txt
no secrets here
[user@host ~]$ grepnot(){ ! grep $1 $2; return $?;}
[user@host ~]$ grepnot password mylogfile.txt 
[user@host ~]$ echo $?
0
[user@host ~]$ grepnot secret mylogfile.txt 
no secrets here
[user@host ~]$ echo $?
1

Note: I'm using 'grepnot' in a Jenkins pipeline. My previous answer used "1 - $?" to reverse the return code. But that solution still caused grep failure in the pipeline. The above solution (which borrows from a previous "!" answer) works with the pipeline.

like image 1
WayneTabor Avatar answered Oct 13 '22 12:10

WayneTabor