test/[在shell脚本中?-d,-e和-f标志有什么区别?

Siv*_*ddy 2 bash shell freebsd

是什么区别-d,-e,-f在shell脚本?我想了解的差异-e,-d-f参数.

例如:if [ -d /path ],if [ -e /path/ ],if [ -f /path ]

据我所知

  • -d 检查目录是否存在
  • -e 检查目录和内容(如果目录中存在内容然后返回true)
  • -f 检查文件是否存在

che*_*ner 6

有几种不同类型的对象可以存在于文件系统中.常规文件和目录只是其中两个; 其他包括管道,套接字和各种设备文件.这是一个使用管道来说明三个选项之间差异的示例.-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
Run Code Online (Sandbox Code Playgroud)

你没有问过它,但有一个-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
Run Code Online (Sandbox Code Playgroud)

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

  • 阻止特殊文件(-b)
  • 字符特殊文件(-c)
  • socket(-S)
  • 符号链接(-h-L两个工作一样,我不记得为什么都定义了历史.)