-1

To test my I created a one-line batch file called Test.bat It contains this...

EXIT /b 3

Now, if I open a Command Window and run it...

C:\Temp>Test.bat & echo %ERRORLEVEL%

I see a "0".

But if I run it again... I get 3! And as many times as I run it, I always get 3.zzz:

Please forgive if this is a dumb beginner question. Can someone please explain... why do I get "0" the first time??

Thanks, Rob-

Gerhard
  • 22,678
  • 7
  • 27
  • 43
Unit1
  • 1
  • 1
    The short answer is: `cmd.exe` first parses always the entire command line with replacing all `%Variable%` by current value of the referenced variable and __then__ executes the command(s) on the command line. So `cmd.exe` first changes the command line to `Test.bat & echo 0` on first execution in a command prompt window, then processes `Test.bat` and executes next `echo 0`. On second execution of the command line the current value of variable `ERRORLEVEL` is `3` and so is executed `Test.bat & echo 3`, i.e. first `Test.bat` and next `echo 3`. – Mofi Feb 14 '22 at 15:26

2 Answers2

1

The problem is that you are trying to access a variable at run time and not at execution time. For this you require delayedexpansion which can be enabled by first running

cmd /V:ON

then run:

test.bat & echo !errorlevel!

You can learn about delayedexpansion by running the following commands from cmd

Specifically for cmd:

cmd /?

and for batch-file related content see:

set /?
setlocal /?
Gerhard
  • 22,678
  • 7
  • 27
  • 43
0

Gerhard already pointed out a possible solution. You can also do something like this. See:

@echo off

call :setError
Echo %errorlevel%
GoTo :eof

:setError
Exit /B 3
SNR
  • 712
  • 1
  • 8
  • 22
  • 1
    What's the point of this, how does this answer the question? – aschipfl Feb 14 '22 at 11:36
  • We'll have to wait and see... Part of answering this questions is guessing what is being asked. @aschipfl. – SNR Feb 14 '22 at 11:39
  • @SNR, the problem here is that if you run `test.bat & echo %errorlevel%` you will get both `3` and `0`. The question was based specific to the issue around `echo`ing of the `errorlevel` directly after running the batch file. This is giving an alternative, not answering the question OP has. – Gerhard Feb 14 '22 at 11:44
  • Gerhard posted a real answer then if you are not mistaken, your answer will be accepted. And I hope I won't be harmed just because I am learning. @Gerhard – SNR Feb 14 '22 at 11:54