Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the POSIX "printable characters" class not match a simple string?

I wrote the following script to test the "printable characters" character class, as described here.

#!/bin/sh

case "foo" in
    *[:print:]*) echo "found a printable character" ;;
    *) echo "found no printable characters" ;;
esac

I expect this script to output found a printable character, at least one (in fact, all) characters in "foo" are printable. Instead, it outputs "found no printable characters". Why are the characters in "foo" not recognized as printable characters?

like image 874
Matthew Avatar asked Feb 20 '23 19:02

Matthew


1 Answers

The string [: is only special inside a bracket expression and bracket expressions are themselves introduced by [. So your example should be:

case "foo" in
    *[[:print:]]*) echo "found a printable character" ;;
    *) echo "found no printable characters" ;;
esac

If this seems cumbersome, think about for example how you would specify a pattern which should match a lowercase letter or a digit but not an upper case letter.

For more information see the section of the POSIX spec detailing bracket expressions in regular expressions. Bracket expressions in shell patterns are like bracket expressions in regular expressions, except for the treatment of ! and ^. (Though otherwise there are other differences between shell patterns and regexes, outside the context of bracket expressions).

like image 130
James Youngman Avatar answered Mar 05 '23 08:03

James Youngman