Open In App

Shell Script to Validate Integer Input

Last Updated : 09 Apr, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Here we are going to see a shell script which validates an integer. We are going to display whether the input entered is an integer or an invalid input. 

Approach: 

  1. Take input from the user.
  2. Store the input of any variable
  3. Now we are going to trim the input in such a way that all the -(minus) or +(plus) signs before the input are trimmed down.
  4. Now we are going to apply a regular expression to check if the input pattern has multiple occurrences of digits 0-9.
  5. If the input pattern contains only digits, this means that the input entered is a valid integer and in all other cases, invalid integer input is shown.

The Shell Script is given below:

# Asking the user to enter an input
echo "Enter an input"

# reading and storing input
read variable

# Applying the approach given above

case ${variable#[-+]} in
  *[!0-9]* | '') echo "Not an integer" ;;
  * ) echo "Valid integer number" ;;
esac

Output:

Shell Script to validate integer input, allow negative integers too

Output of the above code snippet


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads