&&(并且) ||(或者)(和)

在上面刚刚提到了分号,用于多条命令间的分隔符。另外还有两个可以用于多条命令中间的特殊符号,那就是 “&&” 和 “||” 下面把这几种情况全列出:

  1. command1 ; command2            

  2. command1 && command2       并且    

  3. command1 || command2          或者

&&:左边命令执行成功才会执行右边的命令。

  || :左边命令执行不成功,才会执行右边的命令。

(分号):左边命令执行成功与否,后边的命令都会执行。

使用 ”;” 时,不管command1是否执行成功都会执行command2;

使用 “&&” 时,只有command1执行成功后,command2才会执行,否则command2不执行;

使用 “||” 时,command1执行成功后command2 不执行,否则去执行command2,总之command1和command2总有一条命令会执行。

在做实验前,想把所有的 test* 删除掉,可是删除的时候,却提示说权限不够,下面是排除问题的过程:

[root@localhost ~]# rm -rf test* rm: 无法删除"test2/test1": 权限不够 rm: 无法删除"test2/test3": 权限不够 rm: 无法删除"test2/test4": 权限不够 [root@localhost ~]# ls test* test1  test3  test4 [root@localhost ~]# lsattr test* -----a-------e- test2/test1 ----i--------e- test2/test3 -------------e- test2/test4 [root@localhost ~]# chattr -a test2/test1 [root@localhost ~]# chattr -i test2/test3 [root@localhost ~]# rm -rf test* rm: 无法删除"test2/test1": 权限不够 rm: 无法删除"test2/test3": 权限不够 rm: 无法删除"test2/test4": 权限不够 [root@localhost ~]# ls test* test1  test3  test4 [root@localhost ~]# ls -ld test* drwxrwxr-x 2 root root 4096 5月  10 10:12 test2 [root@localhost ~]# ls -l test2/* -rw-r--r-- 1 root root 6 5月  10 10:20 test2/test1 -rw-r--r-- 1 root root 0 5月  10 10:11 test2/test3 -rw-r--r-- 1 root root 0 5月  10 10:12 test2/test4 [root@localhost ~]# lsattr test2/* -------------e- test2/test1 -------------e- test2/test3 -------------e- test2/test4 [root@localhost ~]# lsattr test2 -------------e- test2/test1 -------------e- test2/test3 -------------e- test2/test4 [root@localhost ~]# lsattr -d test2 ----i--------e- test2 [root@localhost ~]# chattr -i test2/ [root@localhost ~]# rm -rf test2/

如果你之前跟着做过同样的实验,相信你也会出现同样的问题的。接下来要通过做实验来说明 “&&” 与 “||” 这两个特殊符号的作用:

[root@localhost ~]# touch test1 test3 [root@localhost ~]# ls test2 && touch test2 ls: 无法访问test2: 没有那个文件或目录 [root@localhost ~]# ls test2 ls: 无法访问test2: 没有那个文件或目录 [root@localhost ~]# ls test2 || touch test2 ls: 无法访问test2: 没有那个文件或目录 [root@localhost ~]# ls test* test1  test2  test3