shell script-判断式

  test判断式

看下面:

1 test -e /opt/a.txt && echo "exist" || echo "not exist"

判断 /opt/a.txt 存不存在,存在输出 exist ,否则输出 not exist

test还有很多用法:

  1. 关于某个文件名的”文件类型“判断,如 test -e fileName 表示判断存在与否
    1. -e 该文件名是否存在
    2. -f  该文件名是否存在且为文件
    3. -d 该文件名是否存在且为目录
  2. 关于文件的权限,如 test -f fileName 表示判断文件是否可读
    1. -r
    2. -w
    3. -x
  3. 关于两个文件之间的比较 ,如 test file1 -nt file2
    1. -nt  (newer than)判断 file1 是否比 file2 新
    2. -ot  (older than)判断 file1 是否比 file2 旧
  4. 关于两个整数之间的判断,如 test n1 -eq n2
    1. -eq 判断相等
    2. -ne 判断不相等
    3. -gt  n1 大于 n2
    4. -lt   n1 小于 n2
    5. -ge  大于等于
    6. -le   小于等于
  5. 关于字符串比较
    1. Test -z string  若string是空字符串,返回true
    2. Test -n string 若string是空字符串,返回false
    3. test str1=str2
    4. test str1!=str2
  6. 多重条件判定
    1.  -a    两个条件同时成立, 如 test -e file1 -a -e file2 ,表示判断 file1 和 file2 是否都存在
    2.  -o    任何一个条件成立就成立,如 test -e file1 -o -e file2,file1 或 file2 任何一个存在都返回 true
    3.  !      否定,如 test ! -e file1,  表示 file1 不存在返回 true

[  ... ] 判断式

经常用于if 语句的判断

注意: [ ] 中每个组件都需要用空格符来分隔; 变量最好都用双引号括起来; 常量也用双引号括起来

原文地址:https://www.cnblogs.com/formyjava/p/4214529.html