简体   繁体   中英

Regex and if in shell script

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"/' 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?

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
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM