当前位置: > shell编程 >

linux shell条件判断包括嵌套判断的例子

时间:2015-03-14 21:59来源:linux.it.net.cn 作者:IT
linux shell条件判断语句的用法,shell if语句的格式,shell多层嵌套语句的写法,以及shell编程中case语句的例子。


shell if语句一般格式:
if command1
then
  command
fi
其中,执行command1 并检测退出状态,如果退出状态为 0 ,就执行then和fi之间的命令。

退出状态(shell条件判断)

每个命令执行完后,都会返回一个退出状态。按照约定,0 表示运行成功。非0 表示运行失败。
管道的退出状态是最后一个命令的退出状态。

grep命令,如果从至少一个文件中找到指定模式,则返回的状态为0,如果没有找到指定模式或出错,返回状态不为0。

$? 保存上一条命令的退出状态
 

user=$1
if who | grep "^$user " > /dev/null
then
  echo "$user is logged on"
fi
test

用来在if 中测试条件 test “$name” = julio # 测试变量是否等于julio.

注意: 这里test 接受的是3个参数。 = 左右必须有空格。 最好把变量用双引号括住。 注意 test 对参数要求严格。如果变量为等号,
 

symbol='='
test -z "$symbol" #会报错,建议采用下面写法
test X"$symbol" = X

因为使用 test 非常频繁,有另一种简明写法。 [ -z “$symbol” ] 注意 [ ] 之间要有空格
 

[  "$name" = julio ]

1、字符串操作符
 

String1  =  String2
String1  != String2
String1不为空
-n String2  不为空
-z String2  为空

2、整数操作符
 

int1 -eq int2 #等于
int1 -ge int2 # 大于等于
int1 -gt int2 # 大于
int1 -le int2 # 小于等于
int1 -lt int2 # 小于
int1 -ne int2 # 不等于
[ "$#" -ne 0 ]

3、文件操作符
 

-d file # file 为目录
-e file # file 存在
-f file #  file 为普通文件
-s file #  file 长度不为0
-r file #  file 为进程可读
-w file #  file 为进程可写
-x file #file 可执行
-L file # file 为链接
[ -f /user/phonebook ]  检测是否存在且为普通文件

4、逻辑操作符

! 取反 -a 逻辑与 -o 逻辑或

例子,检测传入参数数目:
 

if [ "$#" -ne 1 ]
then
  echo "Incorrect number of arguments"
  echo "Usage: on user"
else
  user="$1"
  if who | grep "^$user " > /dev/null
  then
 echo "$user is logged on"
  else
 echo "$user is not logged on"
  fi
fi
exit

shell 中有一个内部命令 exit,可以直接退出程序。
exit n # 为希望的退出状态,如果不指定,使用之前命令的退出状态
例子:
 

if [ "$#" -ne 1 ]
then
  echo "Incorrect number of arguments"
  echo "Usage: on user"
  exit 1
fi
elif

当if有多层嵌套时,可以使用elif。

例子:
 

#!/bin/bash
hour=$( date | cut -c12-13 )
if [ "$hour" -ge 0 -a "$hour" -le 11 ]
then
 echo "Good morning"
elif [ "$hour" -ge 12 -a "$hour" -le 17 ]
then
 echo "Good afternoon"
else
 echo "Good evening"
fi

shell case语句,发现匹配后,执行命令直到双分号处。

例如:
 

case "$1"
  in
 0) echo zero;;
 1) echo one;;
esac

可以在case 中使用特殊匹配符 : ? 表示任一字符 * 表示任意字符 [..] 表示方括号中的任一一个字符
 

case "$1"
  in
 [ 0-9 ] ) echo 数字;;
 [ a-z ] ) echo 小写字母;;
 *  )
# ;;
esac

还可以用 | 表示或
 

case "$hour"
  in
 0? | 1[01] ) echo "早上";;
 1[2-7] ) echo "下午";;
 *# ) echo "晚上";;
esac
 

空命令

在一些情况下,因为语法要求必须写一个命令, 可以用 : 表示

if 命令的另一种形式

命令1 && 命令2 当命令1 返回0时,执行命令2 命令1 || 命令2 当命令1 返回不为0时,执行命令2

这种形式,可以嵌套,也可以用在if 中。
 

# 类似逻辑与
if validsys "%sys" && timeok
then
  sendmail $user@$says < $message
fi

# 类似逻辑或
if validsys "%sys" || timeok
then
  sendmail $user@$says < $message
fi

 


(责任编辑:IT)
------分隔线----------------------------
栏目列表
推荐内容