1

I want this to only output "match!" if only the single character "a" or "b" is passed as an argument. Not aaaaa, not bcfqwefqef, not qwerty.

#!/bin/bash
P="a|b"
if [[ "$1" =~ $P  ]]; then
    echo "match!"
else
    echo "no!"
fi

Yes i've gone through some SO posts to get this far already. Putting $P in quotes doesn't work either.

1 Answer 1

6

You need to anchor your regex:

#!/bin/bash

re="^(a|b)$"
if [[ "$1" =~ $re ]]; then
    echo "match!"
else
    echo "no!"
fi

btw this doesn't require regex. You can just use equality using glob pattern as:

if [[ "$1" == [ab] ]]; then
    echo "match!"
else
    echo "no!"
fi
Sign up to request clarification or add additional context in comments.

4 Comments

The ^(...)$ wrapping is what i needed, the real world use case was strings longer than a and b
You might still be able to use pattern matching: "$1 == (long string a|long string b|long string c), for instance. Pattern matching is typically simpler if the choices are quite specific.
@chepner Needs @(pattern1|pattern2), no?
Yeah, I was thinking of case syntax.

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.