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

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
noprogrammer
Posts: 36
Joined: 29 Oct 2009 11:55

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

#1 Post by noprogrammer » 25 Jan 2019 04:50

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...

Aacini
Expert
Posts: 1914
Joined: 06 Dec 2011 22:15
Location: México City, México
Contact:

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

#2 Post by Aacini » 25 Jan 2019 08:47

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

noprogrammer
Posts: 36
Joined: 29 Oct 2009 11:55

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

#3 Post by noprogrammer » 26 Jan 2019 06:23

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.

Post Reply