Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if string matches a regex in POSIX shell? (not bash)

Tags:

I'm using Ubuntu system shell, not bash, and I found the regular way can not work:

#!/bin/sh string='My string';  if [[ $string =~ .*My.* ]] then    echo "It's there!" fi 

error [[: not found!

What can I do to solve this problem?

like image 609
harryz Avatar asked Jan 14 '14 13:01

harryz


1 Answers

Using grep for such a simple pattern can be considered wasteful. Avoid that unnecessary fork, by using the Sh built-in Glob-matching engine (NOTE: This does not support regex):

case "$value" in   *XXX*)  echo OK ;;   *) echo fail ;; esac 

It is POSIX compliant. Bash have simplified syntax for this:

if [[ "$value" == *XXX* ]]; then :; fi 

and even regex:

[[ abcd =~ b.*d ]] && echo ok 
like image 200
gavenkoa Avatar answered Oct 24 '22 14:10

gavenkoa