shell脚本之if分支
此文仅作记录,原文地址:https://blog.csdn.net/chengqiuming/article/details/78601946
一、if格式
if [ condition ] --注意括号两边有空格,condition 是个条件表达式
then
commands
fi
做用:判断 condition 条件是否成立,若是成立,执行中间的命令 commands,不成立不执行。
如: if [ $a -gt $b ]
then
echo "a大于b"
fi
if 能够接 条件表达式 (如 if [ $a -gt $b ]),也能够直接接一个命令(如 if mkdir /abc ) ,这时,会把命令的执行结果做为判断,若是成功执行,就至关于条件成立,若是执行不成功,就至关于条件不成立。
code
二、if else格式
if condition
then
command1
command2
...
commandN
else
command
fi
三、if else-if else格式
if condition1
then
command1
elif condition2
command2
else
commandN
fi
if else语句常常与test命令结合使用,以下所示:
io
num1=$[2*3]
num2=$[1+5]
if test $[num1] -eq $[num2]
then
echo 'The two numbers are equal!'
else
echo 'The two numbers are not equal!'
fi
输出:
The two numbers are equal!
class
四、if的嵌套
格式一:
if [ condition ]
then
if [ condition ]
then
commands1
else
commands2
fi
fi
格式二:
if [ condition ]
then
if [ condition ]
then
commands1
else
commands2
fi
else
commands3
fi
五、多条件表示:
逻辑与
if [ condition1 -a condition2 ]
或 if [ condition1 ] && [ condition2 ]
逻辑或
if [ condition1 -o condition2 ]
或 if [ condition1 ] || [ condition2 ]
逻辑非(取反)
!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构