Reading exit code value when executing bat file from other bat file.

Posted by p_lider May 6th, 2011

If you have to execute a bat file from other bat file, you normally use CALL command to achieve your goal. Everything works fine until you want to retrieve exit code of called bat file (the %ERRORLEVEL% environmental variable) when you executed the CALL command within IF clause.  The problem is that that the %ERRORLEVEL% variable will not change its value after calling other bat file until we leave the  IF clause!

So to sum up – always read %ERRORLEVEL% variable outside any IF clause. Not doing so will cause wrong exit code to be retrieved. This is very strange behavior which made me to spend all day searching what is wrong with my BAT files not working.

2 Responses

  1. luk says:

    Bash rules! :)

  2. Kris says:

    The same problem is when you are inside “for loop”

    E.g.

    for %%F in (*.*) do (
    call a.bat

    rem you don’t have access to variables set in a.bat
    )
    rem this is the first line when you can use a.bat variables ;/

    BATCH SUCK!