If you want an input which contains only alphanumeric characters i.e. 1-9 or a-z lower case as well as upper case characters, We can make use of regular expression or Regex in short in a Shell Script to verify the input.
Input: Geeksforgeeks Output: True Explanation: Here all the inputted data are alphanumeric Input: Geeks@for@geeks Output: False Explanation: @ is not alphanumeric
Here our task is to write a script to take inputs a variable, and it checks that the input string from start to end has only numbers or alphabets(lower or upper case). If there are any other special characters the condition in the while loop will evaluate to false and hence the while loop will get executed, and it inputs the variable again, and then it again checks for the while loop condition of alphanumeric characters. The loop will continue until the user inputs only alphanumeric and non-empty string or number. \
#!/bin/bash # Input from user read -p "Input : " inp # While loop for alphanumeric characters and a non-zero length input while [[ "$inp" =~ [^a-zA-Z0-9] || -z "$inp" ]] do echo "The input contains special characters." echo "Input only alphanumeric characters." # Input from user read -p "Input : " inp #loop until the user enters only alphanumeric characters. done echo "Successful Input"
The following screenshot of the test case of the code is executed, and it only accepts non-empty alphanumeric input. It even rejects an empty input and other characters excluding alphabets and numbers. The following code is a regular expression to check for numbers or alphabets from start(^) till the end($) and a condition of empty input ( -z stands for the length of zero). So, the shell script will prompt the user again and again until he/she inputs an alphanumeric character.