语法结构如下:
1. if-then语句
# if-then语句 if command #根据conmmand的退出状态码,选择执行语句
then
commands
fi e.g.
#!usr/bin/bash
testuser=rich
if grep $testuser /etc/passwd
then
echo The bash files for user $testuser are:
ls -a /home/$testuser/
fi
2. if-then-else语句
#!usr/bin/bash
if command #根据conmmand的退出状态码,选择执行语句
then
commands
else
commands
fi
3. 嵌套if(elif)
#!usr/bin/bash
if command
then
commands
elif command
then
commands
elif command
then
commands
else
commands
fi
4. test命令(单测试条件)
# 主要有3类测试条件
* 数值比较: -eq; -ge; -gt; -le; -lt; -ne.
* 字符串比较:=; !=; \<; \>; -n; -z.
* 文件比较:-d; -e; -f; -r; -s; -w; -x; -O; -G; -nt; -ot. #usr/bin/bash
if test condition
then
commands
fi #!usr/bin/bash
if [ condition ] # condition前后又空格
then
commands
fi
5. 复合条件测试
# AND测试:必须同时满足两个条件(真)
if [ condition1] && [ condition2 ]
then
commands
fi #OR测试:满足任何一个条件(任一为真)
if [ conditon1 ] || [ condition2 ]
then
commands
fi
6. if-then高级特性
# 双圆括号:用于数学表达式
(( expression ))
# 常用表达式:val++; val--; ++val; --val; !(逻辑求反); ~(位求反); **; <<(位左移); >>(位右移); &位布尔‘和’及‘或’; |; 逻辑‘和’及‘或’:&&; ||;
if (( expression ))
then
commands
(( expression ))
fi # 双方括号:用于字符串表达式(e.g. 正则表达式)
[[ expression ]] if [[ expression ]]
then
commands
fi
7. case命令
# 将指定的变量同不同的模式进行比较 case variable in
pattern1 | pattern2)
commands1;;
pattern3)
commands2;;
*)
commands3;;
esac