grep -E or egrep exit status.

thefirefly

New Member
Credits
19
Hi
For example, I have a text file contains the words below.

$cat sometext.txt
call
attended

Executed below
$egrep 'call|attended' sometext.txt
call
attended
$ echo $?
0
As excepted the exit status is 0
Now egrep with a word that is not in sometext.txt

$ egrep 'call|zzz' sometext.txt
call
$ echo $?
0
This is because 'call' is in sometext.txt.

I wanted the exit to be 1 as long as a word is not sometext.txt.
How can I do that?
Thanks
 


jpnilson

New Member
Credits
266
The exit code will only tell you that command ran correctly. You could get the desired affect using some bash code. I'm sure this could be done more elegantly but the test below counts instances of a word. If both words are present an exit code of 0 is returned. If the test fails a 1 is returned.


#!/bin/bash

test1=$(egrep -c 'call' sometext.txt)
test2=$(egrep -c 'attended' sometext.txt)
if [ $test1 -gt 0 ] && [ $test2 -gt 0 ]
then
exit 0
else
exit 1
fi
 
$100 Digital Ocean Credit
Get a free VM to test out Linux!


Top