在 shell 脚本中,测试 / [ 中的 -d、-e 和 -f 标志有什么区别



shell脚本中的-d-e-f有什么区别?我试图了解-e-d-f参数之间的区别。

示例:if [ -d /path ]if [ -e /path/ ]if [ -f /path ]

据我所知

  • -d检查目录是否存在
  • -e检查目录和内容(如果存在包含内容的目录,则返回 true(
  • -f检查文件是否存在

几种不同类型的对象可以存在于文件系统中。常规文件和目录只是其中的两个;其他包括管道、套接字和各种设备文件。下面是使用管道的示例,用于说明这三个选项之间的差异。 -e只是检查命名参数是否存在,而不管它实际上是什么。 -f-d要求其参数既存在又属于适当的类型。

$ mkfifo pipe   # Create a pipe
$ mkdir my_dir  # Create a directory
$ touch foo.txt # Create a regular file
$ [ -e pipe ]; echo $?   # pipe exists
0
$ [ -f pipe ]; echo $?   # pipe exists, but is not a regular file
1
$ [ -d pipe ]; echo $?   # pipe exists, but is not a directory
1
$ [ -e my_dir ] ; echo $?  # my_dir exists
0
$ [ -f my_dir ] ; echo $?  # my_dir exists, but is not a regular file
1
$ [ -d my_dir ] ; echo $?  # my_dir exists, and it is a directory
0
$ [ -e foo.txt ] ; echo $?  # foo.txt exists
0
$ [ -f foo.txt ] ; echo $?  # foo.txt exists, and it is a regular file
0
$ [ -d foo.txt ] ; echo $?  # foo.txt exists, but it is not a directory
1

您没有询问它,但有一个-p选项可以测试对象是否为管道。

$ [ -p pipe ]; echo $?    # pipe is a pipe
0
$ [ -p my_dir ]; echo $?  # my_dir is not a pipe
1
$ [ -p foo.txt ]; echo $?  # foo.txt is not a pipe
1

其他类型的条目,以及用于测试它们的命令:

  • 块特殊文件 ( -b (
  • 字符特殊文件 ( -c (
  • 插座 ( -S (
  • 符号链接(-h-L的工作方式相同;我不记得为什么两者都被定义的历史。

这一切都在"man test"中解释,或者拼写为"man ["。

https://www.freebsd.org/cgi/man.cgi?test

最新更新