sfyhip 发表于 2018-8-22 12:05:10

DAY11 Shell脚本基础(Enginner05-2)

六、条件测试及选择

6.1 测试表达式
  -file状态测试

6.1.1 [ -e file ]
  file存在,值为true;file不存在为false

6.1.2 [ -d file ]
  file存在并且为目录,值为true;file不存在为false

6.1.3 [ -f file ]
  file存在并且为文件,值为true;file不存在为false

6.1.4 [ -r file ]
  file有r权限,值为true;file没有r权限,值为false

6.1.5 [ -w file ]
  file有w权限,值为true;file没有w权限,值为false

6.1.6 [ -x file ]
  file有x权限,值为true;file没有x权限,值为false
  -整数大小测试

6.1.7 [ x -gt y ]
  x>y

6.1.8 [ x -ge y ]
  x≧y
  大于等于

6.1.9 [ x -eq y ]
  x=y
  等于

6.1.10 [ x -ne y ]
  x!=y
  不等于

6.1.11 [ x -lt y]
  x< y
  小于

6.1.12 [ x -le y ]
  x≦y
  小于等于
  -字符串测试

6.1.13 [ 'x' == 'y' ]
  'x'与'y'相同
  字符串测试

6.1.14 [ 'x' != 'y' ]
  'x'与'y'不同
  字符串测试

6.1.15 [ -n &quot;string&quot;]
  判断string是否有值,有值为true,没有值为false

6.1.16 [ -z &quot;string&quot;]
  判断string是否为空,为空则为true,不为空则为false
  -多重条件判定

6.1.17 -a
  and 与

6.1.18 -o
  or 或

6.2 if条件测试

6.2.1 if单循环
  if 条件测试;then
  command xx
  fi

6.2.2 if双循环
  if 条件测试;then
  command xx
  else
  command yy
  fi

6.2.3 if多循环
  if 条件测试;then
  command xx
  elif 条件测试1;then
  command yy
  else
  command zz
  fi

6.2.4 空值与没有的区别
  空值表示值为空
  没有表示不存在
  &quot;$1&quot; == redhat #给变量加上双引号可以将&quot;没有&quot;变成&quot;空值&quot;
  脚本举例:
  

#!/bin/bash  if [ "$1" == redhat ];then
  echo fedora
  elif [ "$1" == fedora ];then
  echo redhat
  else
  echo '/root/foo.sh redhat|fedora' >&2 # >&2表示这个echo为错误输出
  
fi
  

6.3 for循环结构
  根据变量值的不同取值,重复执行相同的操作,直到变量里没有值以后退出循环
  for 变量名 in 值列表
  do
  command xx
  done


页: [1]
查看完整版本: DAY11 Shell脚本基础(Enginner05-2)