wannabe programmer
wannabe programmer

Reputation: 683

How to check if a string contains a specific character

I've been trying to make a condition in a bash script which will tell me if the given string contains chars other than letters or a hyphen.

i.e, this is a legal string: hello-world

and that one is not: hello-123-there

This is what I have tried so far but I think I also have a logic mistake:

if ! [[ "$1" == *-* ]] && ! [[ "$1" =~ ^[a-zA-Z]+$ ]] ; then
        echo "the line is bad"
        exit
fi

(while $1 refers to the string, of course). Would love to get some help from you.

Upvotes: 2

Views: 1143

Answers (1)

anubhava
anubhava

Reputation: 785571

You can use regex features of BASH:

[[ "$str" =~ ^[a-zA-Z-]*$ ]] && echo "valid" || echo "invalid"

OR using glob:

[[ "$str" == *[^-[:alpha:]]* ]] && echo "invalid" || echo "valid"

Which is same as:

if [[ "$str" =~ ^[a-zA-Z-]*$ ]]; then
    echo "valid"
else
    echo "invalid"
fi

Upvotes: 3

Related Questions