linux命令--test

来源:互联网 发布:福建护理网络教育 编辑:程序博客网 时间:2024/05/21 22:38


test 命令主要用于检测比较文件的类型和权限,另外也能简单比较字符串和整数。
test的结果是true或false,但不会显示在屏幕上,需要$?(上一次程序或脚本的退出码) 或 && 及 || 来展示。


[root@localhost ~]# test -e /andy  && echo "exist" || echo "Not exist"
Not exist


具体功能分类
1,关于某个档名的‘文件类型’的判断。
如 上面的 # test -e /andy ,就表示 /andy这个文件是否存在(linux中文件又很多种,-e表示任意类型)
# test -d /andy 表示/andy这个目录是否存在
-f 表示普通文件
-d 表示目录
-L 表示连结档
其他 -b,-c,-S,-p对应相应的文件类型
2,文件权限检测。
如#test -r /andy 表示/andy这个文件是否可读(当然会首先判断是否存在);
-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  依据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 $PATH  && echo "exist" || echo "Not exist" 结果是 exist
test -z string  若 string 为空字符串,则为 true 
test -n string 若 string 为空字符串,则为 false。  -n 可省略 
test str1 = str2  若相等,则回传 true 
test str1 != str2 若相等,则回传 false 
6,复合的判断
-a (and)两状况同时成立! 
-o (or)两状况任何一个成立!
!  反相状态,如 test ! -x file ,当 file 不具有 x 时,回传 true 
如 #test -r filename -a -x filename  表示filename文件同时具有可读和可执行属性时返回true
0 0