【问题标题】:What is the difference between the -d, -e , and -f flags in test / [ in shell scripting?shell 脚本中 test / [ 中的 -d、-e 和 -f 标志有什么区别?
【发布时间】:2017-08-18 10:28:43
【问题描述】:

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

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

据我所知

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

【问题讨论】:

  • 您要查找的文档位于man test

标签: bash shell freebsd


【解决方案1】:

有几种不同类型的对象可以存在于文件系统中。常规文件和目录只是其中的两个;其他包括管道、套接字和各种设备文件。这是一个使用管道的示例来说明三个选项之间的差异。 -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 的工作方式相同;我不记得为什么定义两者的历史了。)

【讨论】:

  • 我想检查目录是否存在,然后将内容移动到备份目录,否则创建新目录 mkdir -p /testdir。你能分享一些示例代码吗?
  • @SivakumarReddy,如果您在编写脚本时遇到困难,请附上脚本in your questiona new question
【解决方案2】:

在“man test”中都有解释,或者拼写为“man [”。

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

【讨论】:

    猜你喜欢
    • 2017-07-29
    • 2011-02-15
    • 1970-01-01
    • 2015-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    相关资源
    最近更新 更多