shell 中比较运算符的使用方法

一、关于 test 的使用

1.关于某个文档的『文档类型』判断,如 test -e filename 表示存在否
-e 该『文档』是否存在?(常用)
-f 该『文档』是否存在且为文件(file)?(常用)
-d 该『文档』是否存在且为目录(directory)?(常用)
-b 该『文档』是否存在且为一个 block device 装置?
-c 该『文档』是否存在且为一个 character device 装置?
-S 该『文档』是否存在且为一个 Socket 文件?
-p 该『文档』是否存在且为一个 FIFO (pipe) 文件?
-L 该『文档』是否存在且为一个连结文档?

2. 关与文档的权限检测,如 test -r filename 表示可读否 (但 root 权限常有例外)
-r 检测该文档是否存在且具有『可读』的权限?
-w 检测该文档是否存在且具有『可写』的权限?
-x 检测该文档是否存在且具有『可运行』的权限?
-u 检测该文档是否存在且具有『SUID』的属性?
-g 检测该文档是否存在且具有『SGID』的属性?
-k 检测该文档是否存在且具有『Sticky bit』的属性?
-s 检测该文档是否存在且为『非空白文件』?
3. 两个文档之间的比较,如: test file1 -nt file2
-nt (newer than)判断 file1 是否比 file2 新
-ot (older than)判断 file1 是否比 file2 旧
-ef 判断 file1 与 file2 是否为同一文件,可用在判断 hard link 的判定上。 主要意义在判定,两个文件是否均指向同一个 inode 哩!
4. 关于两个整数之间的判定,例如 test n1 -eq n2
-eq 两数值相等 (equal)
-ne 两数值不等 (not equal)
-gt n1 大于 n2 (greater than)
-lt n1 小于 n2 (less than)
-ge n1 大于等于 n2 (greater than or equal)
-le n1 小于等于 n2 (less than or equal)
5. 判定字串的数据
test -z string 判定字串是否为 0 ?若 string 为空字串,则为 true
test -n string 判定字串是否非为 0 ?若 string 为空字串,则为 false。
注: -n 亦可省略
test str1 = str2 判定 str1 是否等于str2 ,若相等,则回传 true
test str1 != str2 判定 str1 是否不等于 str2 ,若相等,则回传 false
6. 多重条件判定,例如: test -r filename -a -x filename
-a (and)两状况同时成立!例如 test -r file -a -x file,则 file 同时具有 r 与 x 权限时,才回传 true。
-o (or)两状况任何一个成立!例如 test -r file -o -x file,则 file 具有 r 或 x 权限时,就可回传 true。
! 反相状态,如 test ! -x file ,当 file 不具有 x 时,回传 true

示例:

#!/bin/bash
#Program
# test
#History
#2015/03/30 woodie first release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
echo -e "Please input a filename. I will check the filename's type AND \
permission.\n\n"
read -p "Input a filename:" filename
test -z $filename && echo "You must input a filename." && exit 0
#两个符号中间有空格,并非!-e
test ! -e $filename && echo "The filename '$filename' do not exist." && exit 0
test -f $filename && filetype="regulare file"
test -d $filename && filetype="directory"
test -r $filename && perm="readable"
test -w $filename && perm="$perm writable"
test -x $filename && perm="$perm executable"
echo "The filename:$filename is a $filetype"
echo "And the permitssions are:$perm"

二、关于[ ]的使用

使用方法参考test,举例说明

#判断文件是否存在
 # [ -e sh08.sh ];
 # [ $? == 0 ] && echo "存在" || echo "不存在";
#判断字符串是否为空
 # $ [ -z $string ];
 # [ $? == 0 ] && echo "空字符串" || echo "非空字符串";
#判断$string是否为空,且sh08.sh
 # [ -z "$string" -a -e sh08.sh ];[ $? == 0 ] && echo "字符串为空,且sh08.sh存在";

要点:

  • 1、在中括号 [ ] 内的每个组件都需要有空白键来分隔
  • 格式:[□$?□==□0□],□表示空格,必须严格按照这个格式。
  • 2、在中括号内的变量,最好都以双引号括号起来;
  • 如果变量中,带有空格,而又没有双引号,则出错
  • 3、在中括号内的常数,最好都以单或双引号括号起来。

shell 中比较运算符的使用方法》上有1条评论

  1. Pingback引用通告: shell 中的运算符 | 精彩每一天

发表评论

电子邮件地址不会被公开。 必填项已用*标注

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>