Alex Rivera | Logout

shell matching a pattern using a case-statement which is stored inside a variable

Asked 2009-10-13T17:46:06.923
11

I am trying to match a pattern with a case-statement where the pattern is stored inside a variable. Here is a minimal example:

PATTERN="foo|bar|baz|bla"

case "foo" in
    ${PATTERN})
        printf "matched\n"
        ;;
    *)
        printf "no match\n"
        ;;
esac

Unfortunately the "|" seems to be escaped (interestingly "*" or "?" are not). How do I get this to work, i.e. to match "foo"? I need to store the pattern in a variable because it is constructed dynamically. This needs to work on a POSIX compatible shell.

Edit
Report

1 Answer

1

Your pattern is in fact a list of patterns, and the separator | must be given literally. Your only option seems to be eval. However, try to avoid that if you can.

answered 2009-10-13T18:06:31.070

Your Answer