大家好,我是博哥爱运维。这节课给大家讲解Shell脚本, 使用条件语句判断数字的大小关系,在前面课程也讲过计算输入两个数字之和,听过前面课程的同学,这节课也可以用来当作复习,以便巩固之前学到的shell语法。
源码:
#!/bin/bash
# 这个脚本演示了如何使用条件语句判断两个数字的大小关系
# 检测是否为数字
checkNum(){
local num=$1
expr $num + 1 &>/dev/null
if [[ $? -ne 0 ]];then
echo "$num 不是一个数字."
exit 1
fi
}
# 提示用户输入第一个数字
echo "Enter the first number:"
read num1
checkNum $num1
# 提示用户输入第二个数字
echo "Enter the second number:"
read num2
checkNum $num2
# 判断大小关系
if [ "$num1" -gt "$num2" ]; then
echo "第一个数字 $num1 大于 第二个数字 $num2."
elif [ "$num1" -lt "$num2" ]; then
echo "第一个数字 $num1 小于 第二个数字 $num2."
else
echo "第一个数字 $num1 等于 第二个数字 $num2."
fi
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...