-
if 语句允许使用逻辑组合进行测试,有两种方式如下:
- 1、[ 表达式 1 ] && [ 表达式 2 ]
- 2、[ 表达式 1 ] || [ 表达式 2 ]
-
命令格式:
if [ 表达式 1 ] && [ 表达式 2 ] then 语句块 else 语句块 fi if [ 表达式 1 ] || [ 表达式 2 ] then 语句块 else 语句块 fi
-
第一个布尔表达式使用的 and 运算符,当 and 运算符两边的表达式都成立时,执行 then后面的语句块,否则执行 else 后面的语句块。
-
第二个表达式使用的是 or 运算符,当 or运算符两边的表达式有一个成立时,执行 then 后面的语句块,否则执行 else 后面的额语句块。下面通过例子说明。
-
-
&&运算符例子:
#!/bin/bash file=/home/hadoop01/bash01/file04 # 判断当前用户是否是 hadoop01,文件存在并且可写 # 当三个表达式同时成立时执行 then 后面的语句块 if [ "$USER" = "hadoop01" ] && [ -f "$file" ] && [ -r "$file" ] then cat $file else echo "$file is not exist!" fi
-
修改上面的脚本,使用-a 代替&&运算符,这样只需要一个方括号并且功能相同。例子:
#!/bin/bash file=/home/hadoop01/bash01/file04 # 判断当前用户是否是 hadoop01,文件存在并且可写 # 当三个表达式同时成立时执行 then 后面的语句块 if [ "$USER" = "hadoop01" -a -f "$file" -a -r "$file" ] then cat $file else echo "$file is not exist!" fi
-
-
||运算符例子:举例说明逻辑或的使用方法,只要||运算符两侧的表达式其中一个成立时,执行 then 后面的语句块。例子:
#!/bin/bash file=/home/hadoop01/bash01 # 判断用户是否是 hadoop01 或者 root if [ "$USER" = "hadoop01" ] || [ "$USER" = "root" ] then cd $file # 判断日志文件是否存在 if [ -f "tmp/logs.log" ] then # 删除日志文件 rm tmp/logs.log fi # 创建一个空的日志文件 touch tmp/logs.log date >> tmp/logs.log else echo "You are not have permission!" fi
-
修改上面的脚本,可以使用-o 代替||运算符,同样可以只使用一个方括号并且实现的功能相同。
#!/bin/bash file=/home/hadoop01/bash01hadoop01 # 判断用户是否是 hadoop01 或者 root if [ "$USER" = "hadoop01" -o "$USER" = "root" ] then cd $file # 判断日志文件是否存在 if [ -f "tmp/logs.log" ] then # 删除日志文件 rm tmp/logs.log fi # 创建一个空的日志文件 touch tmp/logs.log date >> tmp/logs.log else echo "You are not have permission!" fi
-