专业的编程技术博客社区

网站首页 > 博客文章 正文

Shell 脚本的 if-else/case 用法(shell脚本ifelse怎么写)

baijin 2024-09-01 13:08:50 博客文章 7 ℃ 0 评论

if-then 语句

if command
then 
	commands 
fi

if-then 的语法和我们熟悉的其他高级编程语言有些差别,以C++为例,if 后面一般是条件判断表达式,通过表达式返回 True or False,来决定运行或者不运行接下来的命令,而Shell 中的 if-then 不同,if 语句会执行其后的命令,如果命令的退出码为 '0', 则执行 then 后的逻辑,如果退出码非 '0',则不执行。'fi' 表示 if-then 逻辑语句的结束。

if-then-else 语句

if command
then 
	commands
else
 commands
fi

if-then-else 语句与if-then 相同,只是当if 后免得command 返回码为非 '0'时,会执行else 语句。

if-then-elif-then 语句

if command1
then 
	commands
elif command2
then
 commands
else
then
 commands
fi

原理其实和if-then-else没有区别,只是增加了逻辑分支的判断匹配。

test 命令

test condition #test命令的格式

if-then 系列的命令中,if语句不能直接判断condition,而只能通过命令的返回码来作为条件判断依据,这有些时候并不便利,而且和我们熟悉的其他高级语言中的 if-else 语法不同。test 命令可以帮助我们转变shell 中的 if-then 结构语法为我们熟悉的语法。标准的结构是:

if test condition
then 
 commands
fi

bash shell中也提供了另一中方法来实现 test 相同的结果, 将condition 用方括号[]括起来

if [ condition ] #方括号和condition之间要有空格
then 
 commands
fi

数值比较

结合上面的内容,举一个例子说明:

输出结果为:

the value of 10 is greater than value of 5
value of 5 is equal to 5

注:bash shell中只能比较整数。

字符串比较

因为字符串比较中,直接用了数学符号,而bash中会将大于号和小于号理解为重定向符号(之前的文章中有介绍重定向的含义和用法),所以做字符串比较是需要对大于号和小于号做转义,转义方式为在 '<' or '>' 之前加 "\". 直接上例子

输出结果为:"hello is less than world"

文件比较

复合条件测试

[ condition1 ] && [ condition2 ] 
[ condition1 ] | | [ condition2 ]

条件判断高级用法

1.使用双圆括号, 且双圆括号内的 '<' or '>' 号不需要转义。

(( expression ))

双圆括号可以使用的表达式更多,如下

2.使用双方括号, 注:并不是所有的bash都支持双方括号语法。

[[ expression ]]

case 命令

shell 中的 case 命令和其他高级语言的用法是一样的,都是为了解决 if-then-elif 太多的情况,可以是代码更清晰。case 语句的格式为

case variable in 
pattern1 | pattern2) command1;;
pattern3) command2;;
*) default commands;;
esac

直接上例子:

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表