shell学习十六--read

前端之家收集整理的这篇文章主要介绍了shell学习十六--read前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
例题1: 如果读入的不是整数或者参数不是两个(可以判断有没有输入内容), 以上shell脚本的执行会有什么结果?如何解决这两个问题? 思考: 1、输入为两个值过关。 2、输入均为整数过关。 3、计算 方法一使用read [root@node01 day6]# vi read1.sh #!/bin/bash read -p "please insert values:" a b expr 1 + $a &>/dev/null A=$? expr 1 + $b &>/dev/null B=$? if [ ! -n "$a" ] || [ ! -n "$b" ] 这里-n是非空,(! -n)可以使用-z then echo "please insert two values!" exit 1 elif [ "$A" -ne 0 ] || [ "$B" -ne 0 ] then echo "plesse insert two zhengshu!" exit 1 else echo "$a-$b =$(($a-$b))" echo "$a+$b =$(($a+$b))" echo "$a*$b =$(($a*$b))" echo "$a/$b =$(($a/$b))" echo "$a**$b =$(($a**$b))" echo "$a%$b =$(($a%$b))" exit 1 fi [root@node01 day6]# sh read1.sh please insert values:3 3 3-3 =0 3+3 =6 3*3 =9 3/3 =1 3**3 =27 3%3 =0 错误输入: [root@node01 day6]# sh read1.sh please insert values:1 f plesse insert two zhengshu! [root@node01 day6]# sh read1.sh please insert values:f f plesse insert two zhengshu! [root@node01 day6]# sh read1.sh please insert values:d please insert two values! 方法二使用传参 [root@node01 day6]# vi read2.sh #!/bin/bash #wolf #qq 1098331428 #v1.0 if [ $# -ne 2 ] then echo "USAGE:$0 num1 num2" exit 1 fi expr $1 + $2 &>/dev/null if [ $? -ne 0 ] then echo "error:please input two numbers" exit 1 else echo "a-b =$(($1-$2))" fi [root@node01 day6]# sh read2.sh 2 3 a-b =-1 [root@node01 day6]# sh read2.sh 2 f error:please input two numbers [root@node01 day6]# sh read2.sh USAGE:read2.sh num1 num2 方法三直接使用expr判断即可 #!/bin/bash echo "this is a calculation script,welcome to use." read -p "pls input:" a b expr $a + $b &>/dev/null if [ $? -eq 0 ] then echo "a-b =$(($a-$b))" else echo "please input two values and they are integer." echo "请输入两个整数,并使用空格隔开" exit fi 原文链接:https://www.f2er.com/bash/389890.html

猜你在找的Bash相关文章