In the shell we often have to face a problem is how to judge my interactive front-end, the user input is a number it? I'm going to have two ways of doing this here, so just say it here today.
The first type: SED format
First: Let's start with the direct output (in the command line), if it's all right and then write in the shell script. ) Direct echo Output
echo "111ASD"
The first step: thinking
And then we'll think about what we're going to say with SED, but what's the main function of sed? Replace!!! Of course it's a replacement, and since it's a replacement, can we just replace the echo output directly and see what's left of the output? If we are left empty, then I can basically be sure that my echo output is empty, if I am not empty after the SED, then I can think I echo output is not a number or not all is a number?
Step two: Command-line testing:
[Email protected] shell]# echo "111ASD" | Sed ' s#[0-9]# #g ' | Cat-a
asd$
[Email protected] shell]# echo "111" | Sed ' s#[0-9]# #g ' | Cat-a
$
Step three: Conduct shell testing
By the second step we can clearly see that the idea is achievable. So in the shell with the-Z (zero)-N (no zero) is fully achievable, so this time we can do script writing test.
#!/bin/bash
##############################################################
# File Name:test.sh
# version:v1.0
# Author:ls
# Created time:2017-02-24 06:25:13
# Description:
##############################################################
#交互式外部读取
Read-p "Pleace input:" A1
#if进行数字判断
If [-Z] $ (echo $a 1 | Sed ' s#[0-9]# #g ') "]
Then
#如果是数字输出yes给 $? A return value of 1 and exits.
echo "Yes"
Exit 1
Else
#如果不是数字输出no给 $? A return value of 1 and exits.
echo "No"
[Email protected] shell]# sh test.sh
Pleace input:1
Yes
[Email protected] shell]# sh test.sh
Pleace input:q1
No
The second method:
This method compares "special" because it must be used above the shell's version 3.0 (Shell--version, the centos6.8 I use is the 4.8 version of the shell)
Here we are going to introduce a character "=~" in the shell, which is a character match in the shell, not to mention the usage directly.
#!/bin/bash
##############################################################
# File Name:test.sh
# version:v1.0
# Author:ls
# Created time:2017-02-24 06:25:13
# Description:
##############################################################
#交互式外部读取
Read-p "Input:" I
#if进行数字判断
if [[$i =~ ^[0-9]*$]]
Then
#如果是数字输出yes给 $? A return value of 1 and exits.
echo "OK"
Exit 1
Else
#如果不是数字输出no给 $? A return value of 1 and exits.
echo "No"
Exit 1
Fi
Let's test it out here.
[Email protected] shell]# sh shuzipanduan.sh
Input:1
Ok
[Email protected] shell]# sh shuzipanduan.sh
Input:123dasd
No
This article is from my study blog, so be sure to keep this source http://shuai12138.blog.51cto.com/10118203/1901055
How to determine if the input is a number in the shell