shell判断式与判断符号[]

13 篇文章 0 订阅

1. 判断式


test命令用于检测文件类型和比较值。
判断文件是否存在:
[work@www sh]$ test -e file.txt  && echo "exist" || echo "not exist"           
not exist
[work@www sh]$ 

检查文件类型:
    -e  文件是否存在   test -e filename
    -f  文件是否存在,且为文件 file
    -d  文件是否存在,且为目录 directory
    -b  文件是否存在,且为block device设备
    -c  文件是否存在,且为character device设备
    -S  文件是否存在,且为Socket文件
    -p  文件是否存在,且为FIFO(pipe)文件
    -L  文件是否存在,且为连接文件

检查文件权限
    -r  文件是否存在,且可读权限
    -w  文件是否存在,且可写权限
    -x  文件是否存在,且可执行权限
    -u  文件是否存在,且具有SUID属性
    -g  文件是否存在,且具有SGID属性
    -k  文件是否存在,且具有 Sticky bit 属性
    -s  文件是否存在,且为 非空白文件

两个文件比较
    -nt  newer than 判断file1是否比file2新  
         test file1 -nt file2
    -ot  older than 判断file1是否比file2旧
    -ef  判断是否为同一文件,可用在判断hard link上,判定两个文件是否指向同一个inode 

两个整数的判断
    -eq  equal 相等,  test n1 -eq n2
    -ne  not equal 不相等
    -gt  greater than 大于
    -lt  less than 小于
    -ge  greater than or equal 大于等于
    -le  less than or equal 小于等于

判定字符串
    test -z string  判断字符串是否为0, string为空,返回true,  test -z string
    test -n string  判断字符串是否非为0, string 为空, 返回false, -n可省略
    test str1 = str2 是否相等
    test str1 != str2 是否不相等

多重条件
    -a 同时成立,and  , test -r file -a -x file : file同时具有rx权限时,返回true
    -o 任意一个成立, or
    !  取反

如下:
#!/bin/bash

test -e pass && echo "file exist"

test -f pass && echo "regular file"

test -d pass && echo "directory"

2. 判断符号[]


判断符号[] 的使用同test基本一样。
[]里面每个组件都需要用空格分隔。
变量最好用引号包围。
#!/bin/bash

name="Bill gates"

[ "$name" == "bill gates" ]

echo $?

地址: http://blog.csdn.net/yonggang7/article/details/40479141

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值