当前位置:网站首页>Shell脚本-if else语句
Shell脚本-if else语句
2022-07-01 08:36:00 【小蜗牛的路】
最简单的用法就是只使用 if 语句,它的语法格式为:
if condition
then
statement(s)
fi
condition是判断条件,如果 condition 成立(返回“真”),那么 then 后边的语句将会被执行;如果 condition 不成立(返回“假”),那么不会执行任何语句。
注意,最后必须以fi来闭合,fi 就是 if 倒过来拼写。也正是有了 fi 来结尾,所以即使有多条语句也不需要用{ }包围起来。
代码1 比较两个数字的大小
#!/bin/bash
read a
read b
if (( $a == $b ))
then
echo "a和b相等"
fi
输出:
84
84
a和b相等
(())是一种数学计算命令,它除了可以进行最基本的加减乘除运算,还可以进行大于、小于、等于等关系运算,以及与、或、非逻辑运算。当 a 和 b 相等时,(( $a == $b ))判断条件成立,进入 if,执行 then 后边的 echo 语句。
代码2
#!/bin/bash
read age
read iq
if (( $age > 18 && $iq < 60 ))
then
echo "你都成年了,智商怎么还不及格!"
echo "快继续学习吧,能迅速提高你的智商。"
fi
输出:
20
56
你都成年了,智商怎么还不及格!
快继续学习吧,能迅速提高你的智商。。
&&就是逻辑“与”运算符,只有当&&两侧的判断条件都为“真”时,整个判断条件才为“真”。
熟悉其他编程语言的读者请注意,即使 then 后边有多条语句,也不需要用{ }包围起来,因为有fi收尾呢。
if else 语句
代码
#!/bin/bash
read a
read b
if (( $a == $b ))
then
echo "a和b相等"
else
echo "a和b不相等,输入错误"
fi
输出:
10
20
a 和 b 不相等,输入错误
从运行结果可以看出,a 和 b 不相等,判断条件不成立,所以执行了 else 后边的语句。
if elif else 语句
注意,if 和 elif 后边都得跟着 then。
代码:输入年龄,输出对应的人生阶段:
#!/bin/bash
read age
if (( $age <= 2 )); then
echo "婴儿"
elif (( $age >= 3 && $age <= 8 )); then
echo "幼儿"
elif (( $age >= 9 && $age <= 17 )); then
echo "少年"
elif (( $age >= 18 && $age <=25 )); then
echo "成年"
elif (( $age >= 26 && $age <= 40 )); then
echo "青年"
elif (( $age >= 41 && $age <= 60 )); then
echo "中年"
else
echo "老年"
fi
输出:
19
成年
100
老年
代码2:输入一个整数,输出该整数对应的星期几的英文表示:
#!/bin/bash
printf "Input integer number: "
read num
if ((num==1)); then
echo "Monday"
elif ((num==2)); then
echo "Tuesday"
elif ((num==3)); then
echo "Wednesday"
elif ((num==4)); then
echo "Thursday"
elif ((num==5)); then
echo "Friday"
elif ((num==6)); then
echo "Saturday"
elif ((num==7)); then
echo "Sunday"
else
echo "error"
fi
输出:
Input integer number: 4
Thursday
运行结果2:
Input integer number: 9
error
边栏推荐
猜你喜欢
随机推荐
factory type_ Id:: create process resolution
Public network cluster intercom +gps visual tracking | help the logistics industry with intelligent management and scheduling
[深度剖析C语言] —— 数据在内存中的存储
目标检测的yolov3、4、5、6总结
IT 技术电子书 收藏
Field agricultural irrigation system
The meaning of yolov5 training visualization index
中小企业固定资产管理办法哪种好?
任务、线程、进程 区别
Glitch free clock switching technology
R语言观察日志(part24)--初始化设置
Advanced API
用C语言编程:用公式计算:e≈1+1/1!+1/2! …+1/n!,精度为10-6
《微机原理》—总线及其形成
长安链同步节点配置与启动
Do you know how data is stored? (C integer and floating point)
15Mo3 German standard steel plate 15Mo3 chemical composition 15Mo3 mechanical property analysis of Wuyang Steel Works
Configuration and startup of Chang'an chain synchronization node
Review of week 280 of leetcode
SPL Introduction (I)









