Reputation: 518
I don't how to use regex properly in bash, i got an error trying to do in this way, what is wrong in that regex verification?
#!/bin/bash
if [ ! $# -eq 1 ]; then
echo "Error: wrong parameters"
else
if [ $1 =~ "[a-z]" ]; then
echo "$1: word"
elif [ $1 =~ "[0-9]" ]; then
echo "$1: number"
else
echo "$1: invalid parameter"
fi
fi
Upvotes: 3
Views: 11343
Reputation: 6973
I have reworked your script and get the expected result with the following:
#!/bin/bash
if [ ! $# -eq 1 ]; then
echo "Error: wrong parameters"
else
if [[ $1 =~ ^[a-z]+$ ]]; then
echo "$1: word"
elif [[ $1 =~ ^[0-9]+$ ]]; then
echo "$1: number"
else
echo "$1: invalid parameter"
fi
fi
You do not need to quote your Regex.
Upvotes: 15
Reputation: 58778
Don't quote the regex, and use double brackets:
[[ "$1" =~ [a-z] ]]
It's not strictly necessary to quote the variable in this specific case, but it doesn't hurt and it's good practice to always quote strings which contain variables because of the very, very numerous pitfalls related to word splitting.
Upvotes: 6