Bash – Check if string contains only alphanumeric
To check if string contains only alphanumeric in Bash scripting, you can use regular expression ^[a-zA-Z0-9]+$
. In this expression ^
matches starting of the string, [a-zA-Z0-9]+
matches one or more lowercase or uppercase alphabets or numeric digits, and $
matches end of the string.
Examples
In the following script, we take a string in str
which contains only alphanumeric characters. We shall programmatically check if string str
contains only alphanumeric characters using regular expression.
example.sh
#!/bin/bash
str="Apple123"
if [[ $str =~ ^[a-zA-Z0-9]+$ ]]; then
echo "String contains only alphanumeric."
else
echo "String does not contain only alphanumeric."
fi
Output
sh-3.2# ./example.sh
String contains only alphanumeric.
Now let us take a value in the string str
such that it not only contains alphanumeric characters, but also some spaces and special characters.
example.sh
#!/bin/bash
str="Apple@12 3"
if [[ $str =~ ^[a-zA-Z0-9]+$ ]]; then
echo "String contains only alphanumeric."
else
echo "String does not contain only alphanumeric."
fi
Output
sh-3.2# ./example.sh
String does not contain only alphanumeric.
References
Conclusion
In this Bash Tutorial, we learned how to check if string contains only alphanumeric characters using regular expression.