On 02/22/2011 07:24 PM, Peng Yu wrote: > Suppose that I have a variable $x, I want to test if the content of $x > match the pattern 'abc*'. If yes, then do something. (The operator == > doesn't match patterns, if I understand it correctly.) > > Is there such a build-in feature in bash? Or I have to rely on some > external program such as perl to test the pattern matching?
Bash provides a few ways to do this that I can think of. One portable way (the one I generally use), is to take advantage of the fact that you can strip prefixes or suffixes from variables if they match some specified pattern. This is portable to all POSIX-compliant sh implementations. (Edit just before send-off: so is Eric Blake's.) If the wildcard matches as a prefix of the variable, then it will no longer compare equal to the variable (and will, otherwise). test "x${var}" != "x${var##abc*}" (Of course, for examples like yours where they just end in a *, the * is unnecessary for the pattern, and you can just check for a prefix of "x${var##abc}"). Bash's special builtin [[ ]] syntax also provides both wildcards, and (much more powerful) extended regexes (roughly similar to Perl regexes; they're what egrep uses). Wildcards: [[ $var == abc* ]] Regex: [[ $var =~ ^abc.* ]] -- HTH, Micah J. Cowan http://micah.cowan.name/