The "shell" Linux shell determines whether the variable entered by the user is a number

Source: Internet
Author: User

This article: Determine whether the user input parameter is a number

How is the calculation done in the shell?

Way One

[[email protected] scripts]# echo $((1+2))  3

Way Two

Note: When using the method two, the requirements must be spaced. If you are using multiplication, the number must be escaped to write as \

How can I tell if the value entered by a user is a numeric character?

First of all, let's look at the use of Echo to calculate the time, the character + number will be what effect.

[[email protected] scripts]# echo $((a+1))1[[email protected] scripts]# echo $((a+2))2

In this case, the shell will calculate the character as zero, if we want to determine whether the user input is a number, then you can use the echo $ ((variable + 1)) to determine, if 1, then the user input is a character, if the number, then the result is not 1.
But this would be a problem, if the user entered a number of 0?

How to use two solutions

[[email protected] scripts]# expr b + 3expr: 非数值参数

Assuming that the user enters a parameter that is a character, then the use of expr will fail to calculate, when $? It's not 0, so we just need to see $? Whether it is 0 determines whether the parameter entered by the user is a number.

Example

"' #!/bin/bash-

Read-p "Please enter a number:" Number
Expr $number + 1 >/dev/null 2>&1
[$?-ne 0] && echo "$number is not number" | | echo "$number is a number"

**执行结果**

[Email protected] scripts]# bash intnumber.sh
Please enter a number:1
1 is a number
[Email protected] scripts]# bash intnumber.sh
Please enter a number:a
A is not number

版权所有:[arppinging](www.arppinging.com)

The "shell" Linux shell determines whether the variable entered by the user is a number

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.