if 语句格式
if 条件
then
Command
else
Command
fi 别忘了这个结尾
If语句忘了结尾fi
test.sh: line 14: syntax error: unexpected end of fi if 的三种条件表达式
if
command
then if
函数
then
命令执行成功,等于返回0 (比如grep ,找到匹配)
执行失败,返回非0 (grep,没找到匹配)
if [ expression_r_r_r ]
then 表达式结果为真,则返回0,if把0值引向then
if test expression_r_r_r
then 表达式结果为假,则返回非0,if把非0值引向then
[ ] && ——快捷if
[ -f "/etc/shadow" ] && echo "This computer uses shadow passwors"
&& 可以理解为then
如果左边的表达式为真则执行右边的语句 shell的if与c语言if的功能上的区别
shell if c语言if
0为真,走then 正好相反,非0走then
不支持整数变量直接if
必须:if [ i –ne 0 ] 但支持字符串变量直接if
if [ str ] 如果字符串非0
支持变量直接if
if (i )
2.[]与判断条件之间也必须有空格
3.]与;之间不能有空格
二,字符串 判断
2.if [ str1!=str2 ];then fi ----当两个字符串不相等时返回真
3.if [ -n str1 ];then fi ----当字符串的长度大于0时返回真 (判断变量是否有值)
4.if [ -z str1 ];then fi ----当字符串的长度为0时返回真
三,数字 判断
2.int1 -ne int2 --不相等
3.int1 -gt int2 --大于
4.int1 -ge int2 --大于等于
5.int1 -lt int2 --小于
6.int1 -le int2 --小于等于
四,文件 判断
2. -w file --用户可写为真
3. -x file --用户可执行为真
4. -f file --文件存在且为正规文件为真
5. -d file --如果是存在目录为真
6. -c file --文件存在且为字符设备文件
7. -b file --文件存在且为块设备文件
8. -s file --文件大小为非0为真,可以判断文件是否为空
9. -e file --如果文件存在为真
五,逻辑判断
1. -a --与
2. -o --或
3. ! --非
附,case用法
case $var in
表达式1)
若干语句...
;;
表达式2)
若干语句...
;;
*)
若干语句
;;
esac
六.算数运算
1.取余数$(($i%100))
$[]表示数学运算$[$i%100]