Linux程序设计(5)第二章:shell程序设计(4)AND/&& OR/| 用法
- 1. AND &&
-
- 1.1 AND 语法
- 1.2 例子
- 2. OR |
-
- 2.1 OR 语法
- 2.2 例子
- 3. 最短路径求值
- 4. 语句块
1. AND &&
1.1 AND 语法
statement1 && statement2 && statement3 ……
都为true 则为true
1.2 例子
[[email protected] hani]# cat andtest.sh
#!/bin/sh
touch file_one
rm -f file_two
if [ -f file_one ] && echo "hello" && [ -f file_two ] && echo "there"
then
echo "in if"
else
echo "in else"
fi
exit 0
结果:
[[email protected] hani]# ./andtest.sh
hello
in else
2. OR |
2.1 OR 语法
statement1 || statement2 || statement3 ||……
有一个为true 则为true
2.2 例子
[[email protected] hani]# cat ortest.sh
#!/bin/sh
rm -f file_one
if [ -f file_one ] || echo "hello" || echo "there"
then
echo "in if"
else
echo "in else"
fi
exit 0
结果:
[[email protected] hani]# ./ortest.sh
hello
in if
3. 最短路径求值
只需执行最少的语句就可确定其结果。不影响返回结果的语句不会被执行。
例子:
[[email protected] hani]# vi or2test.sh
#!/bin/sh
if ( [ -f file_one ] && echo "hello" ) || [ -d file_one ]
then
echo "in if"
else
echo "in else"
fi
exit 0
结果:
-
有file_one 时
[[email protected] hani]# ./or2test.sh
hello
in if
- 没有file_one时 打印 in if
4. 语句块
用 {} 构造语句块