关于shell命令中嵌入if判断
2012-03-31 16:26
190 查看
Almost all programming languages provide an if statement for controlling the flow of a program based upon the result of a test. This simple example illustrates one acceptable format of the UNIX shell's if statement: |
if [ -f unixfile ] then rm unixfile fi |
This snippet of code will remove (delete) the file named unixfile if it exists and is a regular file. The -f enclosed within brackets performs this test. These two UNIX commands, the -f test and the remove statement, can be combined and compacted into a single line of code by using the && shell construct: |
[ -f unixfile ] && rm unixfile |
This statement is read, if command1 is true (has an exit status of zero) then perform command2. The || construct will do the opposite: |
command1 || command 2 |
If the exit status of command1 is false (non-zero), command2 will be executed. UNIX pipelines may be used on either side of && or ||, and both constructs can be used on the same line to simulate the logic of an if-else statement. Consider the following lines of code: |
if [ -f unixfile ] then rm unixfile else print "unixfile was not found, or is not a regular file" fi |
Using && and || together, this block of code can be reduced to: |
[ -f unixfile ] && rm unixfile || print "unixfile was not found, or is not a regular file" |
Finally, multiple commands can be executed based on the result of command1 by incorporating braces and semi-colons: |
command1 && { command2 ; command3 ; command4 ; } |
If the exit status of command1 is true (zero), commands 2, 3, and 4 will be performed. These two UNIX shell constructs are very powerful tools for any shell script programmer's arsenal. |
These two UNIXshell constructs are very powerful tools for any shell script programmer'sarsenal.
相关文章推荐
- shell基础之二:条件判断语句if、case及read命令,
- 续写vim,shell脚本基础编辑,read命令,if与case判断语句,文件查找方式,压缩与解压,
- shell命令if判断条件简单记载
- shell脚本结构、date命令、变量 shell脚本中的逻辑判断 文件目录属性判断 if特殊用法 case判断
- shell if 条件判断的命令
- centos shell脚本编程1 正则 shell脚本结构 read命令 date命令的用法 shell中的逻辑判断 if 判断文件、目录属性 shell数组简单用法 $( ) 和${ } 和$(( )) 与 sh -n sh -x sh -v 第三十五节课
- shell 命令 if [ -d filename] 判断文件
- linux中shell命令执行的判断依据 &&,||, (),{}
- Shell 编程5(条件判断语句if)
- shell--if条件判断
- Shell if 命令参数
- 关于shell命令的定向输出 2>&1
- shell中条件判断if中的-a到-z的意思
- shell中条件判断if中的-z到-d的意思
- Shell if else命令
- Makefile中怎么使用Shell if判断
- bash shell if 命令参数说明
- (C#)Windows Shell 外壳编程系列4 - 上下文菜单(iContextMenu)(二)嵌入菜单和执行命令
- shell脚本----if判断条件
- shell中的if判断