GREP: variable in regular expression

If I want to look whether a string is alphanumeric and shorter than a certain value, say 10, I would do like this (in BASH+GREP):

if grep '^[0-9a-zA-Z]\{1,10\}$' <<<$1 ; then ...

(BTW: I'm checking for $1, i.e. the first argument)

What if I want the value 10 to be written on a variable, e.g.

UUID_LEN=10
if grep '^[0-9a-zA-Z]\{1,$UUID_LEN\}$' <<<$1 ; then ...

I tried all sort of escapes, braces and so on, but could not avoid the error message

grep: Invalid content of \{\}

After googling and reading bash and grep tutorials I'm pretty convinced it can't be done. Am I wrong? Any way to go around this?

Upvotes: 3

Views: 6167

Answers (1)

chepner
chepner

Reputation: 531165

You need to use double quotes so that the shell expands the parameter before passing the resulting argument to grep:

if grep "^[0-9a-zA-Z]\{1,$UUID_LEN\}$" <<<$1 ; then ...

bash can perform regular expression matching itself, without having to start another process to run grep:

if [[ $1 =~ ^[0-9a-zA-Z]{1,$UUID_LEN}$ ]]; then

Upvotes: 3

Related Questions