Shell 文件测试运算符 | 实例讲解

  目录

一、文件测试运算符

二、常用实例

2.1 -d file 检测目录 

2.2 -f file 检测普通文件

2.3 -x file 检测文件可执行

2.4 -e file 检测文件/目录存在

2.5 -b file 检测块设备文件

三、总结


在 Shell 编程中,文件测试运算符使用的很广泛,经常需要检测一个文件的属性,下面结合实例进行说明。

一、文件测试运算符

表1 文件测试运算符表
操作符 说明                                                  
-b file 检测文件是否是块设备文件,如果是,则返回 true。
-c file 检测文件是否是字符设备文件,如果是,则返回 true。
-d file 检测文件是否是目录,如果是,则返回 true。
-f file 检测文件是否是普通文件(既不是目录,也不是设备文件),如果是,则返回 true。
-g file 检测文件是否设置了 SGID 位,如果是,则返回 true。
-u file 检测文件是否设置了 SUID 位,如果是,则返回 true。
-k file 检测文件是否设置了粘着位(Sticky Bit),如果是,则返回 true。
-p file 检测文件是否是有名管道,如果是,则返回 true。
-r file 检测文件是否可读,如果是,则返回 true。
-w file 检测文件是否可写,如果是,则返回 true。
-x file 检测文件是否可执行,如果是,则返回 true。
-s file 检测文件是否为空(文件大小是否大于0),不为空返回 true。
-e file 检测文件(包括目录)是否存在,如果是,则返回 true。

二、常用实例

2.1 -d file 检测目录 

#!/bin/bash

file="/root"
if [ -d $file ]
then
    echo "$file is directory!"
else
    echo "$file is not directory!"
fi

输出:

[root@localhost Shell]# ./dir.sh 
/root is directory!
[root@localhost Shell]#

2.2 -f file 检测普通文件

#!/bin/bash

file="/root/regularFile"
if [ -f $file ]
then
    echo "$file is regular file!"
else
    echo "$file is not regular file!"
fi

输出:

[root@localhost Shell]# ./dir.sh 
/root/regularFile is regular file!
[root@localhost Shell]#

2.3 -x file 检测文件可执行

#!/bin/bash

file="/root/Shell/dir.sh"
if [ -x $file ]
then
    echo "$file is executable file!"
else
    echo "$file is not executable file!"
fi

输出:

[root@localhost Shell]# ls -l dir.sh 
-rwxr-xr-x. 1 root root 145 2月   6 10:54 dir.sh
[root@localhost Shell]# ./dir.sh 
/root/Shell/dir.sh is executable file!
[root@localhost Shell]#

2.4 -e file 检测文件/目录存在

#!/bin/bash

file="/root"
if [ -e $file ]
then
    echo "$file is exist!"
else
    echo "$file is not exist!"
fi

输出:

[root@localhost Shell]# ./dir.sh 
/root is exist!
[root@localhost Shell]#

2.5 -b file 检测块设备文件

#!/bin/bash

if [ -b /dev/sda ]
then
    echo "/dev/sda is Block Device File!"
else
    echo "/dev/sda is not Block Device File!"
fi

输出为:

[root@localhost Shell]# ./dir.sh 
/dev/sda is Block Device File!
[root@localhost Shell]#

三、总结

文件测试运算符在 Shell 编程中经常使用,几个常用的运算符要记住。

参考文献:

[1] https://www.cnblogs.com/GyForever1004/p/8457028.html

猜你喜欢

转载自blog.csdn.net/u011074149/article/details/113476550
今日推荐