Windows bat 脚本:如何判断文件是否存在?

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

Windows bat script: how to judge if a file exists?

windowsbatch-filedos

提问by Bin Chen

Pseudo code:

伪代码:

if file exists:
do
    xxxx
done
else:
do
    xxxx
done

回答by Mark Wilkins

You can use exist:

您可以使用exist

if exist somefile.dat echo It exists

Depending on the "dialect", you can use elsestatements. At the lowest level, though, some rather ugly logic like this works:

根据“方言”,您可以使用else语句。然而,在最低级别,一些像这样相当丑陋的逻辑是有效的:

if exist somefile.dat goto fileexists
echo file does not exist
goto alldone

:fileexists
echo file exists

:alldone

回答by Mechaflash

Syntax is as follows:

语法如下:

IF [NOT] EXIST filename command

IF [NOT] EXIST 文件名命令

You can use the [NOT] option to execute code if a file doesn't exist as opposed to if the file does exist, however this can be done as an ELSE staement in a standard IF EXIST statement.

如果文件不存在,您可以使用 [NOT] 选项来执行代码,而不是文件确实存在,但是这可以作为标准 IF EXIST 语句中的 ELSE 语句来完成。

IF EXIST stuff.txt (
  ECHO It exists
) ELSE (
  ECHO It doesn't exist
)