当前位置: 首页 > news >正文

【linux】(30)shell-条件判断

if 语句

if 语句是 Shell 脚本中用于条件判断的基本结构。

基本语法

if 语句的基本语法如下:

if [ condition ]
thencommands
fi
  • condition 是要测试的条件。
  • commands 是在条件为真时要执行的命令。

示例

简单条件判断

#!/bin/bashif [ 1 -eq 1 ]
thenecho "1 is equal to 1"
fi

if-else 语句

if-else 语句允许你在条件为假时执行其他命令。

#!/bin/bashif [ 1 -eq 2 ]
thenecho "This will not be printed"
elseecho "1 is not equal to 2"
fi

if-elif-else 语句

if-elif-else 语句允许你测试多个条件。

#!/bin/bashnum=3if [ $num -eq 1 ]
thenecho "The number is 1"
elif [ $num -eq 2 ]
thenecho "The number is 2"
elseecho "The number is neither 1 nor 2"
fi

条件测试

数值比较

  • -eq:等于
  • -ne:不等于
  • -lt:小于
  • -le:小于等于
  • -gt:大于
  • -ge:大于等于
#!/bin/basha=5
b=10if [ $a -lt $b ]
thenecho "$a is less than $b"
fi

字符串比较

  • =:等于
  • !=:不等于
  • <:小于(在 ASCII 顺序上)
  • >:大于(在 ASCII 顺序上)
  • -z:字符串为空
  • -n:字符串不为空
#!/bin/bashstr1="hello"
str2="world"if [ "$str1" = "$str2" ]
thenecho "The strings are equal"
elseecho "The strings are not equal"
fi

文件测试

  • -e filename:文件存在
  • -r filename:文件可读
  • -w filename:文件可写
  • -x filename:文件可执行
  • -d filename:文件是目录
  • -f filename:文件是普通文件
  • -s filename:文件非空
#!/bin/bashfile="test.txt"if [ -e "$file" ]
thenecho "File exists"
elseecho "File does not exist"
fi
http://www.lryc.cn/news/500385.html

相关文章:

  • docker安装启动问题解决排查
  • 《MySQL 查询进阶:复杂查询语句的魅力》
  • OpenHarmony-3.HDF框架(2)
  • 人大金仓(KingBaseEs)数据库操作手册
  • Flink+Paimon实时数据湖仓实践分享
  • w~深度学习~合集1
  • KVM 虚拟化
  • MONI后台管理系统-数据库设计
  • Rigol DP711自动控制--SCPI命令
  • 总结FastDFS的面试题
  • Fiddler 5.21.0 使用指南:过滤浏览器HTTP(S)流量下(四)
  • 【踩坑】pip安装依赖卡在Installing build dependencies ...
  • 【WRF-Urban】SLUCM新增空间分布城市冠层参数及人为热排放AHF代码详解(下)
  • 云桌面:云计算桌面
  • WPF+LibVLC开发播放器-音量控制和倍速控制
  • 数智运营一体化平台项目经营分享
  • 记录blender学习过程中遇到的问题
  • (八)腾讯cloudstudio+Stable-Diffusion-webui AI绘画教程-安装插件
  • 记一次跑前端老项目的问题
  • 深度学习:MindSpore自动并行
  • python拆分Excel文件
  • Python实现Excel中数据条显示
  • c#如何开发后端
  • 6.Vue------async/await详细的讲解---知识积累
  • Redis面试专题-持久化
  • 如何将快捷指令添加到启动台
  • ansible自动化运维(二)ad-hoc模式
  • 技术栈6:Docker入门 Linux入门指令
  • OPStack Optimism Layer2
  • Leetcode—1498. 满足条件的子序列数目【中等】