码迷,mamicode.com
首页 > 系统相关 > 详细

[Linux] 结构化命令 if

时间:2016-12-22 13:58:50      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:文件   expr   bsp   括号   选择   测试   span   高级特性   command   

语法结构如下:

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语句

1 #!usr/bin/bash
2 if command     #根据conmmand的退出状态码,选择执行语句
3 then
4     commands
5 else
6     commands
7 fi

3. 嵌套if(elif)

 1 #!usr/bin/bash
 2 if command
 3 then
 4     commands
 5 elif command
 6 then
 7     commands
 8 elif command
 9 then
10     commands
11 else
12     commands
13 fi

4. test命令(单测试条件)

 1 # 主要有3类测试条件
 2     * 数值比较
 3     * 字符串比较
 4     * 文件比较
 5 
 6 #usr/bin/bash
 7 if test condition
 8 then
 9     commands
10 fi
11 
12 #!usr/bin/bash
13 if [ condition ] # condition前后又空格
14 then
15     commands
16 fi

5. 复合条件测试

 1 # AND测试:必须同时满足两个条件(真)
 2 if [ condition1] && [ condition2 ]
 3 then
 4     commands
 5 fi
 6 
 7 
 8 #OR测试:满足任何一个条件(任一为真)
 9 if [ conditon1 ] || [ condition2 ]
10 then
11     commands
12 fi

6. if-then高级特性

 1 # 双圆括号:用于数学表达式
 2     (( expression ))
 3 
 4 if (( expression ))
 5 then
 6     commands
 7     (( expression ))
 8 fi
 9 
10 # 双方括号:用于字符串表达式(e.g. 正则表达式)
11     [[ expression ]]
12 
13 if [[ expression ]]
14 then
15     commands
16 fi

7. case命令

 1 # 将指定的变量同不同的模式进行比较
 2 
 3 
 4 case variable in
 5 pattern1 | pattern2)
 6     commands1;;
 7 pattern3)
 8     commands2;;
 9 *)
10     commands3;;
11 esac

 

[Linux] 结构化命令 if

标签:文件   expr   bsp   括号   选择   测试   span   高级特性   command   

原文地址:http://www.cnblogs.com/xiaofeiIDO/p/6210617.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!