31. if 条件下的文件测试运算符


在 Linux 中,一切都被视为文件,包括目录、块设备、字符设备或传统的常规文件。 因此,下面的所有测试都称为文件测试运算符。

在下面的所有解释中,常规文件 有一个特殊的含义:它是文件系统中的一个文件。 例如 /etc/passwd文件 一词本身可以是任何类型的文件(目录、块设备、常规文件等)。

文件测试运算符 描述
-e 文件存在(可以是常规文件、目录、块设备、字符设备等)
-f 这是一个常规文件(例如:/etc/passwd
-d 它是一个目录(例如:/etc
-b 它是一个块设备(例如:/dev/sda1
-c 它是一个字符设备(例如:/dev/tty1
-s 文件不为空
-p 它是管道
-S 它是socket
-h 这是一个符号链接
-t 检查给定的 FD 是否在终端中打开。
-r 文件有读权限
-w 文件有写权限
-x 文件有执行权限
-u 文件上设置了 suid
-g 文件上设置了 sgid
-k 文件上设置了 sbit(粘着位、粘滞位、防删除位,只有自己和 root 才有权利修改或删除该文件)
-O 您拥有该文件
-G 文件组 id 和我的组 id 相同。
-N 自上次读取以来该文件是否已被修改?
file1 -nt file2 文件 1 比文件 2 新
file1 -ot file2 文件 1 比文件 2 旧
file1 -ef file2 file1 和 file2 都硬链接到同一个文件
注意:您可以通过在他们前面添加!来反转上述任何条件的含义。

正如我们上面所解释的,文件可以是任何东西。 因此,以下所有内容都将返回 true

  • -e /etc
  • -e /etc/passwd
  • -e /dev/sda

某些文件存在示例:

$ cat if-exists.sh
if [ -e /etc/ ]; then
    echo "/etc directory exists"
fi

if [ -e /etc/passwd ]; then
    echo "/etc/passwd regular file exists"
fi

if [ -e /dev/sda1 ]; then
    echo "/dev/sda1 block device file exists"
fi

if [ -e /dev/tty1 ]; then
    echo "/dev/tty1 character device file exists"
fi

if [ -e /etc/rc.local ]; then
    echo "/etc/rc.local symbolic link file exists"
fi

执行上面的shell脚本来查看输出。

$ ./if-exists.sh
/etc directory exists
/etc/passwd regular file exists
/dev/sda1 block device file exists
/dev/tty1 character device file exists
/etc/rc.local symbolic link file exists

您可能想知道特定目录、链接或块设备是否存在。 使用适当的文件测试条件(如下面的下一个示例所示)进行此测试。

注意:对于大多数文件存在场景,您将测试目录是否存在或常规文件是否存在。 我总是更喜欢使用–d–f–b–h来指定我要查找的文件的确切类型,而不是使用–e

以下示例说明了如何测试特定文件类型

$ cat if-file-type-exists.sh
if [ -d /etc/ ]; then
    echo "/etc exists and it is a directory"
fi

if [ -f /etc/passwd ]; then
    echo "/etc/passwd exists and it is a regular file"
fi

if [ -b /dev/sda1 ]; then
    echo "/dev/sda1 exists and it is a block device"
fi

if [ -c /dev/tty1 ]; then
    echo "/dev/tty1 exists and it is a character device"
fi

if [ -h /etc/rc.local ]; then
    echo "/etc/rc.local exists and it is asymbolic link"
fi

–r–w–x分别检查指定文件(或目录)是否具有读、写和执行权限:

$ cat if-file-permission-exists.sh
filename=/etc/passwd

if [ -r $filename ]; then
    echo "You have read permission on $filename";
fi

if [ -w $filename ]; then
    echo "You have write permission on $filename";
fi

if [ -x $filename ]; then
    echo "You have execute permission on $filename";
fi

注意:尝试从 root非 root 帐户进行权限测试示例,以查看不同级别的访问权限。

您可以在前面使用!反转任何测试条件的含义。 例如,–s检查文件是否不为空。 如果你想检查文件是否为空,请使用! –s

$ cat if-file-empty.sh
if [ -s /etc/passwd ]; then
    echo "/etc/passwd is not empty"
fi

touch /tmp/file1
if [ ! -s /tmp/file1 ]; then
    echo "/tmp/file1 is empty!"
fi

$ ./if-file-empty.sh
/etc/passwd is not empty
/tmp/file1 is empty!