bash “if -e”和“if -f”之间的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10204562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:57:10  来源:igfitidea点击:

Difference between 'if -e' and 'if -f'

bashif-statement

提问by Ahatius

There are two switches for the ifcondition which check for a file: -eand -f.

if检查文件的条件有两个开关:-e-f

What is the difference between those two?

这两者有什么区别?

回答by Emil Vatai

See: http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html

请参阅:http: //tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html

I believe those aren't "if switches", rather "test switches" (because you have to use them inside [] brackets.

我相信那些不是“if 开关”,而是“测试开关”(因为你必须在 [] 括号内使用它们。

But the difference is:

但不同的是:

[ -e FILE ]True if FILE exists.

[ -e FILE ]如果 FILE 存在,则为真。

This will return truefor both /etc/hostsand /dev/nulland for directories.

这将返回真正的两个/etc/hosts/dev/null和目录。

[ -f FILE ]True if FILE exists and is a regular file. This will return truefor /etc/hostsand falsefor /dev/null(because it is not a regular file), and falsefor /devsince it is a directory.

[ -f FILE ]如果 FILE 存在并且是常规文件,则为真。这将返回truefor/etc/hostsfalsefor /dev/null(因为它不是常规文件),以及falsefor/dev因为它是一个目录。

回答by jman

$ man bash

       -e file
              True if file exists.
       -f file
              True if file exists and is a regular file.

A regular file is something that isn't a directory, symlink, socket, device, etc.

常规文件不是目录、符号链接、套接字、设备等。

回答by Ignacio Vazquez-Abrams

-echecks for anytype of filesystem object; -fonlychecks for a regular file.

-e检查任何类型的文件系统对象;-f检查常规文件。

回答by gitaarik

The if statement actually uses the program 'test' for the tests. You could write if statements two ways:

if 语句实际上使用程序“test”进行测试。您可以通过两种方式编写 if 语句:

if [ -e filename ];

or

或者

if test -e filename;

If you know this, you can easily check the man page for 'test' to find out the meanings of the different tests:

如果您知道这一点,您可以轻松查看“test”的手册页以找出不同测试的含义:

man test