shell中test命令参数详解

参考资料 《鸟哥的linux私房菜-基础篇》
test命令一般用来测试一个文件是否存在或者是否有某个权限,以及两个对象的比较等等

文件类型判断

	示例命令 test -e filename
  		-e :该文件是否存在
  		-f :该文件是否存在且是file类型
  		-d : 该文件是否存在且为目录
  		-b:该文件是否存在且为block device装置
  		-c:该文件是否存在且为character device装置
  		-S:该文件是否存在且为Socket文件
  		-p:该文件是否存在且为pipe文件
  		-L:该文件是否存在且为连接档

文件权限测试

	示例命令 test -r filename
	-r:该文件是存在且具有可读属性
	-w:该文件是否存在且具有可写属性
	-x:该文件是否存在且具有可执行权限
	-u:该文件是否存在且具有SUID
	-g:该文件是否存在且具有SGID
	-k:该文件是否存在且Sticky bit属性
	-s:该文件是否存在且为非空白文件

两文件之间的比较

	示例命令 test  file1 -nt file2
	-nt:(newer than)file1是否比file2新
	-ot: (older than)file1是否比file2旧
	-ef:判断file1与file2是否为同一文件

两整数间的判断

	示例命令 test n1 -eq n2
	-eq :两整数是否相等   equal
	-ne: 两整数不相等    not equal
	-gt:  n1是否比n2大    great than
	 -lt:  n1是否比n小       less than
	 -ge:n1是否大于等于n2 greater than or equal
	 -le:n1是否小于等于n2   less than or equal

判断字符串

	示例命令  test -z string  
	-z:判断字符串是否为0.若为空字符串,返回true,否则返回false
	-n:判断字符串是否非为0。若为空字符串,则返回false,否则返回false
	另外 判断两个字符串是否相等或不等,还可以用 == 或 != 判断,和其他语言一样

多重条件判断

	-a  作用就是and 如 test -r file -a -x file 只有当file有读,可执行权限才返回true
	-o	  作用就是or  如 test -r file -o -x file 当file有读,可执行权限,只要有一个满足就返回true
	!反状态	如 test ! -r file 当file没有可读权限时返回true

猜你喜欢

转载自blog.csdn.net/zgq_hw/article/details/87980455