Bash – Check if string contains only alphabets

To check if string contains only alphabets in Bash scripting, you can use regular expression ^[a-zA-Z]+$. In this expression ^ matches starting of the string, [a-zA-Z]+ matches one or more lowercase or uppercase alphabets, and $ matches end of the string.

Examples

In the following script, we take a string in str which contains only alphabets. We shall programmatically check if string str contains only alphabets using regular expression.

example.sh

</>
Copy
#!/bin/bash
 
str="HelloWorld"

if [[ $str =~ ^[a-zA-Z]+$ ]]; then
  echo "String contains only alphabets."
else
  echo "String does not contain only alphabets."
fi

Output

sh-3.2# ./example.sh 
String contains only alphabets.

Now let us take a value in the string str such that it not only contains alphabets, but also some spaces and digits.

example.sh

</>
Copy
#!/bin/bash
 
str="Hello World 123"

if [[ $str =~ ^[a-zA-Z]+$ ]]; then
  echo "String contains only alphabets."
else
  echo "String does not contain only alphabets."
fi

Output

sh-3.2# ./example.sh 
String does not contain only alphabets.

References

Bash If Else

Conclusion

In this Bash Tutorial, we learned how to check if string contains only alphabets using regular expression.