'Win batch: setting variable within nested loop not working
I have a long script that I have condensed to the following lines of code to illustrate the issue I am having. I have tried some suggestion by StackOverflow users to no avail, so hopefully your feedback will help me and future users. NOTE: this code works, except for setting the pdfREP nested variable.
SETLOCAL enabledelayedexpansion
set pdfREP=false
for /f "tokens=1" %%a in ('dir /o /b \\path2document\*.rp?') do (
findstr "," \\path2log\%%a > 1.log
if not errorlevel 0 (
:: do something
)
if errorlevel 0 (
findstr /B /I "p" \\path2document\%%a > 1.log
if errorlevel == 0 (
set pdfREP=true
echo RSP File: %%a >> 2.log
)
)
)
Basically the issue is that in \path2document I have multiple files, and within each I look for a comma. If no comma is found then I want to know if there is a particular letter inside the file's text. If the text is found, the I am setting a previously defined variable to TRUE, instead of FALSE. However, the "if errorlevel == 0" can be true if different syntax (%errorlevel%==0,%errorlevel% EQU 0), and it will NOT set the variable pdfREP to TRUE. If the issue is that the variable is not set until after the loop iteration, then how can I use this variable in the rest of my code? I would like to use this variable later on, so setting it is most important. Thanks for any feedback.
Solution 1:[1]
You are misusing the IF command and the errorlevel value.
IF command description indicate that you may directly use in the condition the ERRORLEVEL word followed by a number indicating a given errorlevel. This way, the following two IF commands are right:
if not errorlevel 0 (
:: do something
)
if errorlevel 0 (
However, the following command is bad written:
if errorlevel == 0 (
In this case, you must use !errorlevel! to indicate to take the current errorlevel value after executing the last line:
if !errorlevel! == 0 (
Independently of the above said, this is the way that I would do that:
if not errorlevel 0 (
echo The errorlevel is less than zero
) else if errorlevel 0 (
echo The errorlevel is greater than zero
) else (
echo The errorlevel is zero
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Aacini |
