1

In a cmd.exe window, when I run python -c "exit(12)" and then run echo %errorlevel%, it prints 12. After that, when I run python -c "exit(13)" & echo %errorlevel%, it prints 12.

Why does the second command fail to print the correct exit code?

indivisible
  • 4,892
  • 4
  • 31
  • 50
userpal
  • 1,483
  • 2
  • 22
  • 38
  • Both commands are being run within the same environment context. If you won't use the `&` operator and run them in sequence it will produce the expected value. Python is irrelevant here. – BartoszKP Jul 13 '14 at 10:08
  • @BartoszKP Actually I need to use Python because I am trying to solve [this problem](http://stackoverflow.com/questions/24555044/why-sometimes-python-subprocess-failed-to-get-the-correct-exit-code-after-runnin). – userpal Jul 13 '14 at 10:20
  • It's irrelevant what *you* are trying to solve. In *this question* Python is irrelevant, as it concerns only the way *cmd* works. I didn't want to edit it out though, as it seems too much, but the question would be more helpful to others if you made it more general. – BartoszKP Jul 13 '14 at 10:32

1 Answers1

3

The substitution of %errorlevel% happens when you run the command. It reflects the value of %errorlevel% when you pressed your 'enter' key.

As an example consider:

> set foo=foo

> echo %foo%
foo

> set foo=bar & echo %foo%
foo

> echo %foo%
bar

You can check the errorlevel like this however:

> python -c 'exit(13)' & if errorlevel 13 echo "its 13"
Jeremy Allen
  • 6,434
  • 2
  • 26
  • 31