1、if-then语句
如果command命令执行成功(退出状态码为0),then部分的命令就会执行
if comand
then
commands
fi
或
if comand: then
commands
fi
例如:
#!/bin/bash
if date
who
then
echo this is test
date
fi
结果:
[root@localhost bin]# ./r.txt
Thu Mar 30 14:51:35 EDT 2017
wcy pts/0 2017-03-30 10:46 (192.168.0.100)
wcy pts/1 2017-03-30 13:47 (192.168.0.100)
this is test
Thu Mar 30 14:51:35 EDT 2017
2、if-then-else语句
如果command命令执行成功(退出状态码为0),then部分的命令就会执行,否则执行else部分
if comand
then
commands
else
commands
fi
3、嵌套if
if comand1
then
commands
elif command2
then
commands
elif command3
then
commands
fi
4、test命令
test condition
可以判断三类条件:数值比较、字符串比较、文件比较
如果条件成立,test命令退出并返回退出状态码0,否则返回1
在if-then语句中使用:
if test condition
then
commands
fi
或
if [ condition ] #方括号内要有一个空格
then
commands
fi
复合条件:[ condition ] && [ condition ] [ condition ] || [ condition ]
5、if-then的高级特性
双尖括号:(( expression )) 用于数学表达式,
expression可以是任意的数学赋值或比较表达式,括号内的大于号不用转义
双方括号:[[ expression ]] 用于高级字符串处理功能,
6、case命令
case variable in
pattern1 | pattern2) commands1;;
pattern3) commands1;;
*) default commands1;;
esac
例如:
#!/bin/bash
case $USER in
root | ww)
echo "welcome,$USER"
date;;
wcy)
echo "welcome,$USER";;
*)
echo "Sorry,you are not allowed here";;
esac
结果:
[root@localhost bin]# ./r.txt
welcome,wcy