温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在Shell脚本中判断用户的输入内容

发布时间:2021-06-05 16:56:15 来源:亿速云 阅读:827 作者:Leah 栏目:开发技术

本篇文章为大家展示了怎么在Shell脚本中判断用户的输入内容,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

1.脚本功能:提示客户属于一串数字,并判断用户是否进行了输入,输入的是否为数字

#!/bin/bash
read -p "enter a number: " number  #提示用户输入数字
if [ -z $number ];then             #判断用户是否输入,如果未输入则打印error
  echo "Error"
  exit
else
  jieguo=`echo "$number*1" | bc `  #把用户的输入值和1相乘,交给bc做运算
  if [ $jieguo -eq 0 ];then          #判断计算结果是否为0,为0则说明number非数字(字符串和0相乘结果为0)
   echo "not a number"
   exit
  fi
fi

怎么在Shell脚本中判断用户的输入内容

Shell脚本中判断输入变量或者参数是否为空的方法,下面总结了5种方法,并分别给出了代码实例,需要的朋友可以参考下

1.判断变量

代码如下:

read -p "input a word :" word
if [ ! -n "$word" ] ;then
  echo "you have not input a word!"
else
  echo "the word you input is $word"
fi

2.判断输入参数

代码如下:

#!/bin/bash
if [ ! -n "$1" ] ;then
  echo "you have not input a word!"
else
  echo "the word you input is $1"
fi

以下未验证。

3. 直接通过变量判断

如下所示:得到的结果为: IS NULL

代码如下:

#!/bin/sh
para1=
if [ ! $para1 ]; then
 echo "IS NULL"
else
 echo "NOT NULL"
fi

4. 使用test判断

得到的结果就是: dmin is not set! 

代码如下:

#!/bin/sh
dmin=
if test -z "$dmin"
then
 echo "dmin is not set!"
else 
 echo "dmin is set !"
fi

5. 使用""判断

代码如下:

#!/bin/sh 
dmin=
if [ "$dmin" = "" ]
then
 echo "dmin is not set!"
else 
 echo "dmin is set !"
fi

下面是我在某项目中写的一点脚本代码, 用在系统启动时:

代码如下:

#! /bin/bash
echo "Input Param Is [$1]"
if [ ! -n "$1" ] ;then
 echo "you have not input a null word!"
 ./app1;./app12;./app123
elif [ $1 -eq 2 ];then
 ./app12;./app123
elif [ $1 -eq 90 ];then
 echo "yy";
fi

上述内容就是怎么在Shell脚本中判断用户的输入内容,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI