教程集 www.jiaochengji.com
教程集 >  脚本编程  >  shell  >  正文 shell中的&&与

shell中的&&与

发布时间:2014-10-18   编辑:jiaochengji.com
本文介绍下,shell中的&&与||运算符的例子,有需要的朋友参考下。

在linxu中,前一个命令执行的结果正确,则Linux会回传一个$?=0的值。
如果要继续根据此回传值来判断后续的指令是否要执行,此时就要考虑使用&&及||运算符。

a href=http://www.jiaochengji.com/jb/shell/ target=_blank class=infotextkeyshell/a &&与||运算符

例一:使用 ls 查阅目录 /tmp/abc 是否存在,若存在则用 touch 建立
 

复制代码 代码示例:
/tmp/abc/hehe 
[root@jbxue ~]# ls /tmp/abc && touch /tmp/abc/hehe
ls: /tmp/abc: No such file or directory 
# ls找不到该目录,但幵没有 touch 癿错误,表示 touch 并没有执行。
[root@jbxue ~]# mkdir /tmp/abc
[root@jbxue ~]# ls /tmp/abc && touch /tmp/abc/hehe
[root@jbxue ~]# ll /tmp/abc
-rw-r--r-- 1 root root 0 Feb  7 12:43 hehe

如果 /tmp/abc 不存在时,touch 就不会被执行,若 /tmp/abc 存在的话,那么 touch 就会开始执行啰!

例二:测试 /tmp/abc 是否存在,若不存在则建立,若存在则不进行任何操作。
 

复制代码 代码示例:
[root@jbxue ~]# rm -r /tmp/abc                <==先初除此目录
[root@jbxue ~]# ls /tmp/abc || mkdir /tmp/abc
ls: /tmp/abc: No such file or directory <==真的不存在喔!
[root@jbxue ~]# ll /tmp/abc                 
total 0                                <==结果出现了!有进行 mkdir

如果要建立 /tmp/abc/hehe 文件,但并不知道 /tmp/abc 是否存在,应该如何操作呢?

例三:不清楚 /tmp/abc 是否存在,但要创建 /tmp/abc/hehe 文件。
 

复制代码 代码示例:
[root@jbxue ~]# ls /tmp/abc || mkdir /tmp/abc && touch /tmp/abc/hehe

分析:
(1)若 /tmp/abc 不存在故回传 $?≠0,则 (2)因为 || 遇到非为 0 的 $?
故开始 mkdir /tmp/abc,由于 mkdir /tmp/abc 会成功执行,所以回传 $?=0 (3)因为 && 遇到 $?=0 故会执行 touch。
(2)若 /tmp/abc 存在故回传 $?=0,则 (2)因为 || 遇到 0 癿 $? 不会执行,此时 $?=0 继续向后传,故 (3)因为 && 遇到$?=0 就开始建立 /tmp/abc/hehe 了!
最终 /tmp/abc/hehe 被建立起来。

您可能感兴趣的文章:
inux shell初级入门教程
C# 注册右键菜单、文件夹与文件的实现代码
深入解析tcsh的初始化配置文件
Solaris shell下操作数据库的方法
shell 生成随机数的例子
学习shell中EOF的用法
shell 求字符串长度的方法
shell中“$”变量的中文说明
Linux Source命令解析
source命令执行shell文件与shell script文件名直接运行的区别

[关闭]
~ ~