目录
- shell中的流控制if语句
- if语句
- if-then语句
- if-then-else 语句
- test命令
- 数值比较
- 字符串比较
- 文件比较
shell中的流控制if语句
简单的脚本可以只包含顺序执行的命令,但结构化命令允许根据条件改变程序执行的顺序。
if语句
if-then语句
if-then语句格式如下:
if command
then
commands
fi
在其他编程语言中, if 语句之后的对象是一个等式,这个等式的求值结果为 TRUE 或 FALSE 。bash shell的 if 语句会运行 if 后面的那个命令。如果该命令的退出状态码是0,位于 then 部分的命令就会被执行。
#!/bin/bash
if pwd
then
echo \”pwd worked\”
fi
输出:
# rob@xx-rob:~$ ./test1/home/robpwd worked
if-then-else 语句
格式:
if command
then
commands
else
commands
fi
示例:
v=bin
if grep $v pwd
then
echo \”pwd worked\”
else
echo \”cannot find $v\”
fi
结果:
rob@xx-rob:~$ ./test1# grep: pwd: 没有那个文件或目录# cannot find bin
if还可以嵌套多层:
if command1
then
command set 1
elif command2
then
command set 2
elif command3
then
command set 3
elif command4
then
command set 4
fi
test命令
bash shell if语句的条件是command,如果要使用常规的数值/字符串比较条件,需要使用test命令。
使用test命令的if-then-fi语句:
if test condition
then
commands
fi
如果不写 test 命令的condition部分,它会以非零的退出状态码退出,并执行 else语句块。
加入条件时,test 命令会测试该条件。
bash shell中 test命令的另外一种写法是使用[ condition ] 中括号,第一个方括号之后和第二个方括号之前必须加上一个空格,否则就会报错。
if中条件判断的几个条件:
- 判断变量是否有值if test ${variable}
- 数值比较
- 字符串比较
- 文件比较
数值比较
test命令的数值比较功能:
#!/bin/bash
if test 100 -le 145; then
echo \”100 is smaller than 145\”
fi
v=12
if [ $v -eq 12 ];then
echo \”value is 12\”
fi
bash shell只能处理整数,不能使用浮点数作为判断条件。
字符串比较
bash shell条件测试还允许比较字符串值,比较字符串比较烦琐。
在bash sehll中比较运算符需要使用转义,否则会被当成重定向运算符。
s1=\”val\”
s2=\”thi\”
# 升成`thi`的文件
if [ $s1 > $s2 ];
then
echo \”new file $v2 has been created.\”
fi
if [ $s1 \\> $s2 ];
then
echo \”$s1 is greater than $s2.\”
fi
比较测试中使用的是标准的ASCII顺序,根据每个字符的ASCII数值来决定排序结果。在比较测试中,大写字母被认为是小于小写字母的。
文件比较
测试Linux文件系统上文件和目录的状态。
if-then 语句允许你使用布尔逻辑来组合测试,有两种布尔运算符可用:
- [ condition1 ] && [ condition2 ]
- [ condition1 ] || [ condition2 ]
case语句
在尝试计算一个变量的值,在一组可能的值中寻找特定值,可能不得不写出很长的 if-then-else语句。case 命令会采用列表格式来检查单个变量的多个值。
case variable in
pattern1 | pattern2) commands1;;
pattern3) commands2;;
*) default commands;;
esac
一个例子:
c=1
case $c in
1 | 2) echo \”1\”;;
3) echo \”23\”;;
esac
到此这篇关于bash shell中的if-then语句的文章就介绍到这了,更多相关shell if-then语句内容请搜索悠久资源网以前的文章或继续浏览下面的相关文章希望大家以后多多支持悠久资源网!
您可能感兴趣的文章:
- Idea使用Bashsupport插件编辑Shell脚本的方法
- shell 脚本中常用的内置变量(Bash 内置变量)
- 浅析Linux之bash反弹shell原理
- 处理Shell脚本中带有空格的变量(bash脚本)
- 详解shell中source、sh、bash、./执行脚本的区别