3

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?

1

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Of course! The answer was so simple! The inverted commas " " will do the trick as differently from ' ' they expand what's inside... the answer. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.