Home > database >  Finding multiple strings in shell scripts
Finding multiple strings in shell scripts

Time:05-09

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?

CodePudding user response:

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.

CodePudding user response:

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 a ? after the space), followed by :.

  • Related