4

I'm moving a bash script to dash for compatibility reasons. Is there a POSIX/Dash alternative to the following comparison?

COMPARE_TO="^(lp:~?|https?://|svn://|svn\+ssh://|bzr://|bzr\+ssh://|git://|ssh://)"

if [[ $COMPARE =~ $COMPARE_TO ]]; then
    echo "WE ARE COMPARED!"
fi
Marco Ceppi
  • 7,163
  • 5
  • 31
  • 43

2 Answers2

10

You can use a case. It doesn't use regex, but it's not that much longer with globs

case $compare in
    lp:*|http://*|https://*|svn://*|svn+ssh://*|bzr://*|bzr+ssh://*|git:/*|ssh://*)
        echo "We are compared"
    ;;
esac

On a side note, you should avoid using all uppercase variable names as you risk overwriting special shell variables or environment variables.

Community
  • 1
  • 1
geirha
  • 5,801
  • 1
  • 30
  • 35
5

dash doesn't have regex comparing built in, but you can always use grep:

if echo "$compare" | egrep -q "$compare_to"; then
    ...

(Note that I second @geirha's note about uppercase variables in the shell.)

Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151
  • `echo` is always a bit scary in this sort of context. The `case` answer is more idiomatic and elegant, and solves the problem entirely without external processes. – tripleee Aug 28 '12 at 19:47
  • @tripleee: I consider the `case` statement's syntax highly inelegant, but I agree it's more idiomatic and saves subprocesses (provided you can express your pattern as a glob rather than a regex, and you can in this particular case). BTW, if you're worried about echo, use `printf "%s\n" "$compare"` instead. – Gordon Davisson Aug 29 '12 at 03:46