%errorlevel% expansion within subroutine
Posted: 14 Oct 2016 18:40
I'm trying to check if md is executed successfully from within a subroutine. The problem is that %errorlevel% will always be 0, even if md has failed to create a directory. It seems that %errorlevel% is expanded before md is executed. This behaviour of %errorlevel% only seems to occur when I try to expand it from within a subroutine.
I don't understand why the expansion of %errorlevel% works that way. In the following code str seems to be expanded after the subroutine getstr is called. From my limited understanding, this seems to contradict the way how %errorlevel% is expanded in the first code.
I know that I could solve the problem by using the || redirection operator to check the result of md or by using delayed expansion and use !errorlevel! instead. Or even adding an extra if exist check.
Unfortunately, this does not help me to understand how exactly %errorlevel% is expanded from within a subroutine and why it always expands to 0. I'm curious to know if there is a neat way to check the result of md while using the original %errorlevel% checking method and not to result to alternative solutions mentioned previously.
Code: Select all
@echo off
setlocal
call :MakeDir "treintje"
exit /b
:MakeDir ( sDirName[in] ) {
if not exist "%~1\*" (
md "%~1" 2> nul
if %errorlevel% neq 0 ( :: will always expand to 0
exit /b
)
)
echo Hi there 1> "%~1\%~1.txt"
exit /b
}
----------------------------------------
Creates a directory and a text file: %cd%\treintje\treintje.txt
Containing the text: Hi there
I don't understand why the expansion of %errorlevel% works that way. In the following code str seems to be expanded after the subroutine getstr is called. From my limited understanding, this seems to contradict the way how %errorlevel% is expanded in the first code.
Code: Select all
@echo off
setlocal
call :func
exit /b
:func
call :getstr str
set "str=%str%, world"
echo %str%
exit /b
:getstr
set /p %1=
exit /b
----------------------------------------
C:\Users\treintje\Desktop>test.bat
Hello
Hello, world
I know that I could solve the problem by using the || redirection operator to check the result of md or by using delayed expansion and use !errorlevel! instead. Or even adding an extra if exist check.
Code: Select all
:MakeDir ( sDirName[in] ) {
if not exist "%~1\*" (
md "%~1" 2> nul || exit /b
)
echo Hi there 1> "%~1\%~1.txt"
exit /b
}
Unfortunately, this does not help me to understand how exactly %errorlevel% is expanded from within a subroutine and why it always expands to 0. I'm curious to know if there is a neat way to check the result of md while using the original %errorlevel% checking method and not to result to alternative solutions mentioned previously.