Page 1 of 1

How to store %Errorlevel% to variable for later use?

Posted: 25 Jan 2019 04:50
by noprogrammer
I need to extend a script by the ability to check the output of a text dump. The script has to know the existence of a specific pattern and should store its state to a variable (0 or 1, basically). The text dump will be some formatted xml output and the pattern looks like <!-- foo:1 --> followed by a linefeed.

I tried the following which doesn't work:

Code: Select all

type foo.log | findstr /r /c:"\<!-- foo:1 --\>" >nul
If %Errorlevel% Equ 0 (
  Echo %Errorlevel%
) Else (
  Echo %Errorlevel%
)
If %Errorlevel%==0 won't work either. The type foo.log will be replaced by a curl command later on.
Instead of the Echo lines I'd like to have some kind of Set ReturnValue=%Errorlevel% instruction as soon as that part works.

If I manually execute the command

Code: Select all

type foo.log | findstr /r /c:"\<!-- foo:1 --\>" >nul
or apply it to a text dump sans pattern:

Code: Select all

type bar.log | findstr /r /c:"\<!-- foo:1 --\>" >nul
I'll correctly get as Echo %Errorlevel% the results 0 and 1.

I wonder where the (logical?) error is...

Re: How to store %Errorlevel% to variable for later use?

Posted: 25 Jan 2019 08:47
by Aacini
In this command there is a pipe:

Code: Select all

type foo.log | findstr /r /c:"\<!-- foo:1 --\>" >nul
The pipe is executed via a new instance of cmd.exe at each side of the pipe. When the pipe (both commands) ends, the errorlevel in each one of the two executed cmd.exe's is lost.

Just use it this way:

Code: Select all

findstr /r /c:"\<!-- foo:1 --\>" foo.log >nul
Antonio

Re: How to store %Errorlevel% to variable for later use?

Posted: 26 Jan 2019 06:23
by noprogrammer
I tried it, it works as well if entered manually, but it won't work in my script.
But I guess I've found the culprit, it's
Setlocal enableDelayedExpansion enableExtensions
The errorlevel handling works as expected without enableDelayedExpansion, however I can't do without it.

I'm unsure what's best practice for my script, but delayed expansion is just used for the first For loop:

Code: Select all

Set/a count=0
For /f "tokens=4,7 delims=<>" %%i In ('curl -s "http://192.168.178.1/login_sid.lua"') Do (
   Set/a count=!count!+1
   Set dummy!count!=%%i
   Set/a count=!count!+1
   Set dummy!count!=%%j
)
Maybe switching it off afterwards will help...

Update: Yes it did: Setlocal disableDelayedExpansion right after the loop fixed it.