1

my programs starts some services and store its output in tmp variable and I want to match the variable's content if it starts with FATAL keyword or not? and if it contains I will print Port in use using echo command

For example if tmp contains FATAL: Exception in startup, exiting.

I can do it by sed: echo $tmp | sed 's/^FATAL.*/"Port in use"/'

but I want to use the builtin if to match the pattern. How can I use the shell built in features to match REGEX?

Mahmoud Emam
  • 1,499
  • 4
  • 20
  • 37
  • 1
    http://stackoverflow.com/questions/12142092/shell-test-operator-regular-expressions `if [[ $tmp =~ ^FATAL.* ]]; then echo "a"; else echo "b"; fi` – Sithsu Aug 15 '13 at 15:55
  • 2
    Which shell? The answer for `bash` will be different from the answer for `csh` or `dash` and maybe from `ksh` too. The comment from @Sithsu applies to `bash`, for example; the answer with `case` will work with shells derived from the Bourne/POSIX shell (not C shell derivatives). – Jonathan Leffler Aug 15 '13 at 15:55
  • Though this question was here earlier, this one has gathered more answers: https://stackoverflow.com/questions/21115121/how-to-check-pattern-match-by-using-bin-sh-not-by-bin-bash. If you don't want `bash`-isms, that's the question to go to. `bash` has its own tool for pattern matching. – Victor Sergienko Mar 11 '20 at 18:25

2 Answers2

5

POSIX shell doesn't have a regular expression operator for UNIX ERE or PCRE. But it does have the case keyword:

case "$tmp" in
  FATAL*) doSomethingDrastic;;
  *) doSomethingNormal;;
esac

You didn't tag the question bash, but if you do have that shell you can do some other kinds of pattern matching or even ERE:

if [[ "$tmp" = FATAL* ]]; then
    …
fi

or

if [[ $tmp =~ ^FATAL ]]; then
    …
fi
kojiro
  • 74,557
  • 19
  • 143
  • 201
  • What's the difference between the second and third answers? – Mahmoud Emam Aug 15 '13 at 16:06
  • 1
    @M_E The second answer uses the `[[` keyword that is similar to the `test` command but has extra features including `case`-like pattern matching. The third answer uses ERE (extended regular expressions). – kojiro Aug 15 '13 at 17:26
1
if [ -z "${tmp%FATAL*}" ]
   then echo "Start with"
 else 
   echo "Does not start with"
 fi

work on KSH, BASH under AIX. Think it's also ok under Linux.

It's not a real regex but the limited regex used for file matching (internal to the shell, not like sed/grep/... that have their own version inside) of the shell. So * and ? could be used

NeronLeVelu
  • 9,908
  • 1
  • 23
  • 43