Young
Young

Reputation: 53

grep 2 words at if statements in Bash

I am trying to see if my nohup file contains the words that I am looking for. If it does, then I need to put that into tmp file.

So I am currently using:

if  grep -q "Started|missing" $DIR3/$dirName/nohup.out
then
  grep -E "Started|missing" "$DIR3/$dirName/nohup.out" > tmp
fi

But it never goes into the if statement even if there are words that I am looking for.

How can I fix this?

Upvotes: 0

Views: 100

Answers (3)

Walter A
Walter A

Reputation: 20002

When you only put the grep results into the tmp-file, you do not want to grep the file twice.
You can not use

egrep "Started|missing" $DIR3/$dirName/nohup.out > tmp

since that would create an empty tmp file when nothing is found. You can remove empty files with if [ ! -s tmp ] or use another solution:

Redirectong the grep results without grepping again can be done with

rm -f tmp 2>/dev/null
egrep "Started|missing" $DIR3/$dirName/nohup.out | while read -r strange_line; do
   echo "${strange_line}" >> tmp
done

Upvotes: 0

Michael Jaros
Michael Jaros

Reputation: 4681

You should use egrep instead of grep (Avinash Raj has explained that in other words already in his answer).

I would generally recommend using egrep as a default for everyday use (even though many expressions only contain the basic regular expression syntax). From a practical point the standard grep is only interesting for performance reasons.

Details about the advantages of grep vs. egrep can be found in that superuser question.

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174706

Since basic sed uses BRE, regex alternation operator is represented by \| . | matches a literal | symbol. And you don't need to touch | symbol in the grep which uses ERE.

if grep -q "Started\|missing" $DIR3/$dirName/nohup.out

Upvotes: 1

Related Questions