0

I am trying to find strings Error:, Error :, ERROR:, ERROR : in a given file, if found then go to if block if not found then go to else block.

Below is the logic I had written to perform this operation.

#!/bin/bash
file='file.log'
text=`cat $file`
echo $text
if [[ ${text} = *Error:* ||${text} = *ERROR:*|| ${text} = *ERROR :* || ${text} = *Error :* || $? -ne 0 ]]; then
  STATUS=1
  echo "=> string found." 
else
  echo "=> no string found." 
fi

Seems like this logic is having issues as its returning below error.

syntax error near `:*'

Can someone please help me in resolving this issue?

4
  • 2
    Why not grep -iq 'error \{0,1\}:' file.log? Commented May 9, 2022 at 10:58
  • Thats indeed a good question, i tried even this it didnt work for me. Please bear with me as i am new to shell scripting. Commented May 9, 2022 at 11:03
  • if ( grep -iq 'error \{0,1\}:' $value || $? -ne 0; ) ; then STATUS=1 echo "=> found string." else echo "=> Didnt found string." fi Commented May 9, 2022 at 11:07
  • still its going to else block though string exists Commented May 9, 2022 at 11:10

2 Answers 2

1

The pattern you’re looking for is easily expressed in a regex, so you can just use grep:

#!/bin/bash

file='file.log'

if grep -iq 'error \{0,1\}:' "${file}"
then
  STATUS=1
  echo "=> string found." 
else
  echo "=> no string found." 
fi

There’s no need to read the whole file into a variable, nor to check $? explicitly.

Sign up to request clarification or add additional context in comments.

Comments

1

This is easier to do using grep, using -i for case insensitive matching and -q to suppress output:

#!/bin/bash
file='file.log'
if grep -iq 'error \?:' "$file"; then
  STATUS=1
  echo "=> string found." 
else
  echo "=> no string found." 
fi

The regular expression error ?: means: the text error, followed by an optional space (indicated by \? after the space), followed by :.

2 Comments

thanks thomas, eventhough i updated my logic still its going to else block.
Sorry, missed a backslash there, fixed now (and tested :)).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.