Batch Script: Return Value Via ErrorLevel Code from Sub Function or Script


The batch script programming can be dated back to the times where the DOS were popular. The batch script, however, is not a real programming language. At the beginning, the batch script contains a list of commands to execute line by line in the file that has the *.bat as file extension. From modern Windows Versions (e.g. XP, Vista, 7, 8, and Win10), the batch scripting has been enhanced greatly, by both external programs and inbuilt commands (e.g. if checks and for loop). And you can also name batch scripts as *.cmd extensions.

If you have a script, e.g. named sub.bat and inside the file, you can use exit /b 123 to exit the script and set the return code to 123 in this case.

C:\Windows\system32>exit /?
Quits the CMD.EXE program (command interpreter) or the current batch
script.

EXIT [/B] [exitCode]

  /B          specifies to exit the current batch script instead of
              CMD.EXE.  If executed from outside a batch script, it
              will quit CMD.EXE

  exitCode    specifies a numeric number.  if /B is specified, sets
              ERRORLEVEL that number.  If quitting CMD.EXE, sets the process
              exit code with that number.

C:\Windows\system32>

Now, at main.bat you can obtain the code by %errorlevel%.

@echo off
call sub.bat
echo %errorlevel%

As we know, the sub functions can be defined as labels, so the content of the sub.bat can be included in the same file,

@echo off
call :sub
echo %errorlevel%
goto exit_label

:sub
exit /b 123

:exit_label

The call command invokes an external script or a sub function/procedure defined by label.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
343 words
Last Post: How to Send Email using VBScript and GMail (SSL)?
Next Post: Create a ShortCut/BookMark in Chrome to the Links Shortener using Javascript

The Permanent URL is: Batch Script: Return Value Via ErrorLevel Code from Sub Function or Script

Leave a Reply