R. Nec
R. Nec

Reputation: 315

Executing batch file breaks when checking if variable has value

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

set /p filevar=file.txt

and check if var is empty:

if "%filevar%"="" exit

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?

Upvotes: 0

Views: 58

Answers (1)

rojo
rojo

Reputation: 24476

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

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.

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

All three statements will have the same result1.

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


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.

Upvotes: 2

Related Questions