Reputation: 683
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
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