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
Indeed, grep returns 0 if it matches, and non-zero if it does not.
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 .
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.
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.
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.
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
[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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With