2

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.

1 Answer 1

3

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

4 Comments

thanks, but - i dont understand the "&&" and "||" usgae, can you plz write the condition? thanks.
Is this what you're looking for?
Plain glob patterns work too: [[ $str == *[^-[:alpha:]]* ]] && echo invalid
That's correct @glennjackman. Thanks editing the answer with this option as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.