windows 如何从批处理文件中检查文件是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4340350/
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 07:50:12  来源:igfitidea点击:

How to check if a file exists from inside a batch file

windowsbatch-file

提问by sab

I need to run a utility only if a certain file exists. How do I do this in Windows batch?

仅当某个文件存在时,我才需要运行实用程序。如何在 Windows 批处理中执行此操作?

回答by Chris J

if exist <insert file name here> (
    rem file exists
) else (
    rem file doesn't exist
)

Or on a single line (if only a single action needs to occur):

或者在一行上(如果只需要执行一个操作):

if exist <insert file name here> <action>

for example, this opens notepad on autoexec.bat, if the file exists:

例如,如果文件存在,这将在 autoexec.bat 上打开记事本:

if exist c:\autoexec.bat notepad c:\autoexec.bat

回答by u109919

C:\>help if

Performs conditional processing in batch programs.

在批处理程序中执行条件处理。

IF [NOT] ERRORLEVEL number command

IF [NOT] string1==string2 command

IF [NOT] EXIST filename command

IF [NOT] ERRORLEVEL 数字命令

IF [NOT] string1==string2 命令

IF [NOT] EXIST 文件名命令

回答by RBerteig

Try something like the following example, quoted from the output of IF /?on Windows XP:

尝试类似以下示例,引用自IF /?Windows XP 上的输出:

IF EXIST filename. (
    del filename.
) ELSE (
    echo filename. missing.
)

You can also check for a missing file with IF NOT EXIST.

您还可以使用IF NOT EXIST.

The IFcommand is quite powerful. The output of IF /?will reward careful reading. For that matter, try the /?option on many of the other built-in commands for lots of hidden gems.  

IF命令非常强大。的输出IF /?将奖励仔细阅读。就此而言,请尝试/?许多其他内置命令的选项,以获取许多隐藏的宝石。