本章内容:
- if-then
- 嵌套if
- test命令
- 复合条件测试
- 使用双方括号和双括号
- case命令
12.1 if-then语句
if command
then
commands
fi
示例:
#!/bin/bash
# testing the if statement
if pwd
then
echo “It worked”
fi
pwd正确执行,退出状态码是0,则if语句成立
注意,这里pwd语句的值也会输出!
12.2 if-then-else语句
if command
then
commands
else
commands
fi
12.3 嵌套if
if command1
then
commands
elif command2
then
more commands
fi
elif (else if),使用elif,只要写一个fi就好了
12.4 test 命令
if test condition
then
commands
fi
另一种写法:
if [ condition ]
then
commands
fi
===
12.4.1 数值比较
e:equals;g:greater; l:less; n:not
示例:
value1=10
value2=11
#
if [ $value1 -gt 5 ]
then
echo "The test value $value1 is greater than 5"
fi
#
if [ $value1 -eq $value2 ]
then
echo "The values are equal"
else
echo "The values are different"
fi
#
※ 不能在test命令中使用浮点值
===
12.4.2 字符串比较
1.比较是否相等
#!/bin/bash
# testing string equality testuser=rich
#
if [ $USER = $testuser ] then
echo "Welcome $testuser"
fi
条件测试语句 [ 符号的两边都要留空格.
条件测试的内容,如果是字符串比较的话, 比较符号两边要留空格!
2.比较字符串顺序
使用大于小于号的时候必须转义,否则shell会把他们理解为重定向符号
#!/bin/bash
val1=baseball
val2=hockey
#
if [ $val1 \> $val2 ]
then
echo "$val1 is greater than $val2"
else
echo "$val1 is less than $val2"
fi
比较测试中认为大写字母是小于小写字母的,而sort命令正好相反。
3.字符串大小
-n和-z可检查一个变量是否含有数据。
#!/bin/bash
# testing string length val1=testing
val2=''
#
if [ -n $val1 ]
then
echo "The string '$val1' is not empty"
else
echo "The string '$val1' is empty"
fi
#
if [ -z $val2 ]
then
echo "The string '$val2' is empty"
else
echo "The string '$val2' is not empty"
fi
===
12.4.3 文件比较
#!/bin/bash
# Look before you leap
jump_directory=/home/arthur
if [ -d $jump_directory ] then
echo "The $jump_directory directory exists"
cd $jump_directory
ls
else
echo "The $jump_directory directory does not exist"
fi
if判定返回值为0的版本
#!/bin/bash
# Look before you leap
if [ -d /home/lyk ];then
echo "The /home/lyk directory exists"
cd /home/lyk
ls
else
echo "The /home/lyk directory does not exist"
fi
12.5 复合条件测试
[ condition1 ] && [ condition2 ]
[ condition1 ] || [ condition2 ]
12.6 if-then的高级特性
12.6.1 使用双括号
(( expression )) 可使用高级运算符
==
12.6.2 使用双方括号
[[ expression ]]
#!/bin/bash
# using pattern matching #4
if [[ $USER == r* ]]
then
echo "Hello $USER"
else
echo "Sorry, I do not know you"
fi
提供了模式匹配
12.7 case命令
case分支语句的格式如下:
case $变量名 in
模式1)
命令序列1
;;
模式2)
命令序列2
;;
*)
默认执行的命令序列 ;;
esac
#!/bin/bash
# using the case command #
case $USER in
rich | barbara)
echo "Welcome, $USER"
echo "Please enjoy your visit";;
testing)
echo "Special testing account";;
jessica)
echo "Do not forget to log off when you're done";;
*)
echo "Sorry, you are not allowed here";;
esac
rich和barbara中间的竖线表示多个匹配