第三章、Linux if case判断语句

 

正文

if 语句

if then fi

单层,单分支

if condition
then
sentence1
sentence2
...
fi

eg:

#! /bin/bash
a=3
b=4
if [ "${a}" -le "${b}" ] && [ "${a}" -ne 2 ]
then
echo "${a} is in the range"
fi

其他格式

if condition; then
sentence1
sentence2
...
fi
#! /bin/bash
a=3
b=4
if [ "${a}" -le "${b}" ] && [ "${a}" -ne 2 ];then echo "${a} is in the range";fi

if then else fi

if condition
then
sentence1
sentence2
...
else
sentence1
sentence2
fi

他也是有其他形式的缩写的,记得有些地方需要加上分号。

#! /bin/bash
filename='expr.sh'
if [ -e "${filename}" ]; then echo "${filename} exist"; else echo "${filename} not exist"; fi

if then elif then elif then fi

if condition
then
sentence1
sentence2
...
elif condition
then
sentence1
sentence2
elif condition
then
sentence1
sentence2
else # 这个 else 可以不要
sentence1
sentence2
fi
#! /bin/bash
a=4
if [ "${a}" -eq 1 ]
then echo "${a}=1"
elif [ "${a}" -eq 2 ]
then echo "${a}=2"
elif [ "${a}" -eq 3 ]
then echo "${a}=3"
else echo "${a} < 1 || ${a} > 3"
fi

case 语句

case "${变量名称}" in
value1)
sentence1
sentence2
...
;; # 类似于 C/C++中的 break
value2)
sentence1
sentence2
...
;; # 类似于 C/C++中的 break
*) # 类似于 C/C++ switch中的 default, * 是模式字符串
sentence1
sentence2
...
;; # 类似于 C/C++中的 break
esac

上文的value是模式字符串,可以使用通配符,如果一个模式字符串中包含多个模式,需要用|分隔开
实例:

#! /bin/bash
choice=$1
echo "choice = ${choice}"
case "${choice}" in
"-a"|"-b") echo "${choice} is -a or -b";;
-[cs]) echo "${choice} is -c or -s";;
*) echo "others"
esac

参考文献

欢迎报名Y总的Linux基础课
Linux 教程(第四版) - 孟庆昌

posted @   lucky_light  阅读(52)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示