本文共 2370 字,大约阅读时间需要 7 分钟。
一般老鸟会建议你不要在 Linux 混用这两个运算符,毕竟理解容易出问题,而且和大部分其他语言里的混用不太一样,我自己也是一知半解。不过非得要杠一下的话,也未尝不可。
我先把 《鸟哥的Linux私房菜》里的一个例子粘出来(很经典的例子):
[root@master ~]# ls exist_file && echo "exist" || echo "not exist"exist_fileexist[root@master ~]# ls no_exist_file && echo "exist" || echo "not exist"ls: cannot access no_exist_file: No such file or directorynot exist[root@master ~]# ls exist_file || echo "not exist" && echo "exist"exist_fileexist[root@master ~]# ls no_exist_file || echo "not exist" && echo "exist"ls: cannot access no_exist_file: No such file or directorynot existexist
&& 表示前一条命令执行成功时,才执行后一条命令,|| 表示上一条命令执行失败后,才执行下一条命令。
Linux 的 && 和 || 和其他语言中的 and 和 or 还是有区别的(比如说和 Python 和 Ruby),特别是当两者混合使用的时候。
[root@master ~]# echo "hello" && echo "world" || echo "nice"# echo "hello" 执行成功,所以 && 后面的 echo "world" 也会执行,因为 # echo "world" 也会执行,所以 || 后面的 echo "nice" 就不再执行。# 可以简单理解为 || echo "nice" 被忽略了helloworld [root@master ~]# echo "hello" || echo "world" && echo "nice"# echo "hello" 执行成功,所以 || 后面的 echo "world" 不再执行,# 可以简单理解为 || echo "world" 被忽略了# 所以上式等价于 echo "hello" && echo "nice",因为 echo "hello" 执行成功,# 所以 && 后面的 echo "nice" 也会成功执行。hellonice
Python 和 Ruby 的例子好理解一些(你只要知道 print 语句本质返回 None 就差不多了, puts 返回 nil):
print("hello") or print("world") and print("nice") 等价于 (print("hello") or print("world")) and print("nice")
print("hello") 执行后返回 False, 而 print("hello") 后边是 or,所以程序还需要判断 or 后边的表达式有没有为 True 的,print("world") 执行后还是返回 False,于是 (print("hello") or print("world")) 为 False;
但是紧接着的后边是 and,而 and 前边已经是 False 了,所以 and 后边的表达式无论是 True 还是 False,整个表达式都必然是 False(所以 print("nice)" 也就没必要再去执行一遍了)。
print("hello") and print("world") or print("nice") 等价于 (print("hello") and print("world")) or print("nice")
print("hello") 执行后返回 False, 而 print("hello") 后边是 and,所以 and 后边的表达式无论是 True 还是 False,(print("hello") and print("world")) 都必然是 False(所以 print("world)" 也就没必要再去执行一遍了);
但是紧接着的后边是 or,所以程序还需要判断 or 后边的表达式有没有为 True 的,所以执行了 print("nice)" 。
Python 3.6.8 (default, Aug 7 2019, 17:28:10) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linuxType "help", "copyright", "credits" or "license" for more information.>>> print("hello") or print("world") and print("nice")helloworld>>> print("hello") and print("world") or print("nice")hellonice
[root@master ~]# pry[5] pry(main)> puts "hello" or puts "world" and puts "nice"helloworld=> nil[6] pry(main)> puts "hello" and puts "world" or puts "nice"hellonice=> nil
转载地址:http://ejjqi.baihongyu.com/