检查变量是否有值时执行批处理文件中断 [英] Executing batch file breaks when checking if variable has value

查看:70
本文介绍了检查变量是否有值时执行批处理文件中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要检查是否加载了文件,我使用以下命令加载其内容:

To chcek if file is loaded or not, I load its contents using:

set /p filevar=file.txt

并检查var是否为空:

and check if var is empty:

if "%filevar%"="" exit

当脚本chceks文件有多行时,脚本的执行停止,因此我认为chcecking失败.为什么脚本失败?如何正确执行这种检查?

When script chceks file with multiple lines, execution of script stops, so i suppose that chcecking fails. Why script fails? How to perform such check properely?

推荐答案

首先,您弄错了set /p命令的语法.照原样,它将以文本"file.txt"提示用户.我想你的意思是

Firstly, you've got the syntax of your set /p command messed up. As it is, it will prompt the user with the text "file.txt". I think what you mean is

set /p "filevar=" <file.txt

如果从命令行运行脚本,还应该将/b开关与exit一起使用,以防止关闭控制台窗口.

You should also use the /b switch with exit to prevent the console window from closing if your script is run from the command line.

但是,正如jeb所说,要检查left是否等于right,请使用==equ.或者,正如dbenham提醒我的那样,如果您要检查一个空值,也可以使用if not defined.

But yeah, as jeb states, to check whether left equals right, either use == or equ. Or, as dbenham reminds me, if you're checking for an empty value, you can also use if not defined.

if "%filevar%"=="" exit /b
if "%filevar%" equ "" exit /b
if not defined filevar exit /b

所有三个语句将具有相同的结果 1 .

All three statements will have the same result1.

在控制台窗口中,输入help if以获得更多信息.

In a console window, enter help if for more information.

1 值得一提的是,尽管这三个if语句在括号代码块之外具有相同的结果,但是只有第三个语句在括号内可以可靠地工作(例如在循环).如果在与%filevar%设置相同的代码块中使用前两个,则需要延迟扩展才能正常工作.

1 It's worth mentioning that, while those three if statements have the same result outside of a parenthetical code block, only the third one will work reliably within parentheses (such as in a for loop). The first two would need delayed expansion to work properly if used within the same code block as %filevar% is set.

这篇关于检查变量是否有值时执行批处理文件中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆