atxdba
atxdba

Reputation: 5216

Regex match for whole string (not substring) in bash

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.

Upvotes: 1

Views: 1301

Answers (1)

anubhava
anubhava

Reputation: 785108

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

Upvotes: 6

Related Questions