exiting batch file within a subroutine - batch-file

I have a Script with different subroutines:
REM ---------------MAIN------------------------START----------------------------
call :SUB_GetStartTime
call :SUB_SettingVariables
call :SUB_CheckingParameters %*
call :SUB_Copy
call :SUB_GetEndTime
call :SUB_WriteLog
call :SUB_EndScreen
REM ---------------MAIN------------------------END------------------------------
At SUB_CheckingParameters I have this if query:
if "%~1"=="/help" (
GOTO SUB_HELP
)
If I pass the parameter /help it goes to my help window:
cls
ECHO ===================HELP==============
ECHO help text help text help text
ECHO =====================================
timeout /t 120
exit /b
after exit /b I want the script to end but it just goes to my next subroutine (SUB_Copy). Shouldnt the script end because I use GOTO SUB_Help and not call ?
Can someone help me and tell me what I am doing wrong?

I ususally handle this by passing back an errorlevel:
#Echo off
REM ---------------MAIN------------------------START----------------------------
call :SUB_GetStartTime
call :SUB_SettingVariables
call :SUB_CheckingParameters %* || Exit /b 1
call :SUB_Copy
call :SUB_GetEndTime
call :SUB_WriteLog
call :SUB_EndScreen
REM ---------------MAIN------------------------END------------------------------
Echo end of main
Pause
Goto :Eof
:SUB_CheckingParameters
if /I "%~1"=="/help" GOTO SUB_HELP
:SUB_GetStartTime
:SUB_SettingVariables
:SUB_Copy
:SUB_GetEndTime
:SUB_WriteLog
:SUB_EndScreen
Echo:We are in %~0 Args %*
Goto :Eof
:SUB_HELP
rem cls
ECHO ===================HELP==============
ECHO help text help text help text
ECHO =====================================
timeout /t 120
exit /b 1

Related

How to call a dynamic label in different .bat file

If I want to call :foo in foo.bat from bar.bat I do:
::foo.bat
echo.wont be executed
exit /b 1
:foo
echo foo from foo.bat
exit /b 0
and
::bar.bat
call :foo
exit /b %errorlevel%
:foo
foo.bat
echo.will also not be executed
But if I don't know the label name but get it passed as a parameter I'm stuck
::bar.bat
:: calling a dynamic label is no problem
call :%~1
exit /b %errorlevel%
::don't know how to "catch-all" or set context of "current-label"
:%~1
foo.bat
You can use a batch parser trick.
You don't need to do anything in foo.bat for this to work
::foo.bat
echo.wont be executed
exit /b 1
:func1
echo foo from foo.bat
exit /b 0
:unknown
echo Hello from %0 Func :unknown
exit /b
You only need to add any labels into bar.bat that you want to call in foo.bat
#echo off
::bar.bat
call :unknown
echo Back from Foo
call :func1
echo Back from Foo
exit /b %errorlevel%
:unknown
:func1
foo.bat
echo NEVER COMES BACK HERE
The trick is that after calling a label in bar.bat and then start foo.bat without calling it (only foo.bat), the foo.bat is loaded and the last called label is jumped to.
Labels are searched by the parser literally before resolving environment variables or argument references, so you cannot use such in labels.
However, hereby I want to provide an approach that allows to use dynamic labels, although I do not understand what is the purpose of that, so this is more kind of an academic answer...
The batch file parser of cmd does not cache a batch file, it reads and executes it line by line, or correctly spoken, it reads and executes each command line/block individually. So we can make use of that and let the batch file modify itself during its execution, given that the modified part lies beyond the currently executed code portion. The following script accomplishes that:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Check whether a label name has been delivered:
if "%~1"=="" (
echo ERROR: No label name specified! 1>&2
exit /B 1
)
rem /* Call sub-routine to replace the literal label string `:%~1`
rem within this batch file by the given dynamic label name: */
call :REPLACE_LINE "%~f0" ":%%%%~1" ":%~1" || (
rem /* In case the given label is `:REPLACE_TEXT`, display error
rem message, clean up temporary file and quit script: */
>&2 echo ERROR: Label ":%~1" is already defined!
2> nul del "%~f0.tmp"
exit /B 1
)
rem // Perform call of the sub-routine with the dynamic label name:
call :%~1
rem /* Call sub-routine to replace the given dynamic label name
rem within this batch file by the literal label string `:%~1`: */
call :REPLACE_LINE "%~f0" ":%~1" ":%%%%~1"
endlocal
exit /B
:REPLACE_LINE val_file_path val_line_LOLD val_line_LNEW
::This sub-routine searches a file for a certain line
::case-insensitively and replaces it by another line.
::ARGUMENTS:
:: val_file_path path to the file;
:: val_line_LOLD line to search for;
:: val_line_LNEW line to replace the found line;
setlocal DisableDelayedExpansion
rem // Store provided arguments:
set "FILE=%~1" & rem // (path of the file to replace lines)
set "LOLD=%~2" & rem // (line string to search for)
set "LNEW=%~3" & rem // (line string to replace the found line)
set "LLOC=%~0" & rem // (label of this sub-routine)
rem // Write output to temporary file:
> "%FILE%.tmp" (
rem /* Read the file line by line; precede each line by a
rem line number and `:`, so empty lines do not appear as
rem empty to `for /F`, as this would ignore them: */
for /F "delims=" %%L in ('findstr /N "^" "%FILE%"') do (
rem // Store current line with the line number prefix:
set "LINE=%%L"
setlocal EnableDelayedExpansion
rem // Check current line against search string:
if /I "!LINE:*:=!"=="!LOLD!" (
rem // Current line equals search string, so replace:
echo(!LNEW!
) else if /I not "!LNEW!"=="!LLOC!" (
rem // Current line is different, so keep it:
echo(!LINE:*:=!
) else (
rem /* Current line equals label of this sub-routine,
rem so terminate this and return with error: */
exit /B 1
)
endlocal
)
)
rem /* Searching and replacement finished, so move temporary file
rem onto original one, thus overwriting it: */
> nul move /Y "%FILE%.tmp" "%FILE%"
endlocal
exit /B
:%~1
::This is the sub-routine with the dynamic label.
::Note that it must be placed after all the other code!
echo Sub-routine.
exit /B
Basically, it first replaces the literal label string (line) :%~1 by the string provided as the first command line argument, then it calls that section by call :%~1, and finally, it restores the original literal label string. The replacement is managed by the sub-routine :REPLACE_LINE.
foo.bat (secondary):
#echo off
echo this is foo.bat
REM check, if the label is defined in this script:
findstr /xi "%~1" %~f0 >nul 2>&1 || goto :error
goto %~1
:foo
echo reached foo.bat, label :foo
exit /b 0
:error
echo wrong or missing label: "%~1"
exit /b 1
bar.bat (primary)
#echo off
echo this is bar.bat
call foo.bat :foo
echo back to bar.bat - %errorlevel%
call foo.bat :foe
echo back to bar.bat - %errorlevel%
call foo.bat
echo back to bar.bat - %errorlevel%
exit /b
As aschipfl already correctly stated you can't have a dynamic label, but you can dynamically call present labels, but you should check for the presence prior calling it like Stephan does but in the primary batch.
So this is a combination of Stephans and jebs batches.
:: bar.bat
#echo off
REM check, if the label is defined in this script:
If "%~1" neq "" findstr /xi "%~1" %~f0 >nul 2>&1||goto :error&&Call :%~1
call :Func1
echo Back from Foo
call :func2
echo Back from Foo
exit /b %errorlevel%
:error
echo wrong or missing label: "%~1"
exit /b 1
:func1
:func2
foo.bat
echo NEVER COMES BACK HERE
:: foo.bat
#Goto :Eof
:func1
echo reached foo.bat, label :func1
exit /b 0
:func2
echo reached foo.bat, label :func2
exit /b 0
Sample output:
> bar
reached foo.bat, label :func1
Back from Foo
reached foo.bat, label :func2
Back from Foo
> bar fx
wrong or missing label: "fx"

how to exit from parent batch context

I 'm trying to create a batch file as below.
#ECHO OFF
:Main
CALL :STEP_1
CALL :STEP_2
GOTO :EXIT
:STEP_1
REM some other logic here
IF %ERRORLEVEL% NEQ 0 (
GOTO :ERROR
)
GOTO :EOF
:STEP_2
REM step 2 logic
GOTO :EOF
:ERROR
EXIT /b 1
:EXIT
EXIT /b 0
What I'm expecting is that the error handling in :STEP_1 will exit from the whole batch file. However, what is happening is that it only exit from the content we created when we use CALL. :STEP_2 will still be called even if there is an error in :STEP_1.
My question is, is it possible to accomplish my requirement? To exit from the whole batch file instead of the :STEP_1 context, so :STEP_2 won't be called.
You can use the following (GOTO) 2>NUL combined with an exit, and that should do the job for you.
:ERROR
(goto) 2>nul & exit /b 1
Refer to this for more information.

Batch-I want to set second part of variable

I have a problem.
set /p command=
if %command% == "display (i want the second part of the variable here)" echo (second part of the variable)
For example, i type:
display hello
I want it to simply:
echo hello
I want to use this for custom commands in my game.
Firstly, you can split the text on firstword|notfirstword with a for /f loop using "tokens=1*". See help for in a console window for full details.
Next, you could use attempt to call :label where :label is whatever the first word was. In essence, you're creating batch functions and letting the user choose which function is executed. If the function label doesn't exist, then errorlevel will be non-zero and you can handle appropriately using conditional execution. This makes it easy to expand your script without having to add an if /i statement for each choice or synonym you add. (It might be a good idea to hide the error message for attempting to call a non-existent label by redirecting 2>NUL.) Here's a full example:
#echo off & setlocal
:entry
set /P "command=Command? "
for /f "tokens=1*" %%I in ("%command%") do (
2>NUL call :%%I %%J || (
if errorlevel 1000 (exit /b 0) else call :unsupported %%I
)
goto :entry
)
:display
:echo
:say
:show
echo(%*
exit /b 0
:ping
ping %~1
exit /b 0
:exit
:quit
:bye
:die
echo OK, toodles.
exit /b 1000
:unsupported <command>
1>&2 echo %~1: unrecognized command
exit /b 0

Call a subroutine in a batch from another batch file

file1.bat:
#echo off
:Test
echo in file one
call file2.bat (Here i want to call only Demo routine in the file2.bat)
file2.bat:
:hello
echo in hello
:Demo
echo in Demo
From the batch file1 I want to make a call to a sub routine in the batch file2.
I tried for example call file2.bat:Demo but it didn't give the correct result.
How I can achieve this?
the file with subroutines must look like:
#echo off
call :%*
exit /b %errorlevel%
:hello
echo in hello
exit /b 0
:Demo
echo in Demo with argument %1
exit /b 0
then from the other file you can call it like
call file2.bat demo "arg-one"
You can write your functions file (in this sample it is library.cmd) as
#echo off
setlocal enableextensions
rem Not to be directly called
exit /b 9009
:test
echo test [%*]
goto :eof
:test2
echo test2 [%*]
goto :eof
:testErrorlevel
echo testErrorlevel
exit /b 1
And then the caller batch can be something like
#echo off
setlocal enableextensions disabledelayedexpansion
call :test arg1 arg2 arg3
call :test2 arg4 arg5 arg6
call :testErrorlevel && echo no errorlevel || echo errorlevel raised
goto :eof
:test
:test2
echo calling function %0
library.cmd %*
:testErrorlevel
echo calling function %0
library.cmd
In this case, the labels need to be defined with the same name in both files.
The direct invocation of the "library" batch file will replace the context of the call :label, and when the invoked batch is readed, a goto :label is internally executed and code continues inside the indicated label. When the called batch file ends, the context is released and the code after the call :label continues.
edited
As Jeb points in comments, there is a drawback in this method. The code running in the called batch file can not use %0 to retrieve the name of the function being called, it will return the name of the batch file. But if needed, the caller can do it as shown in the sample code.
edited 2016/12/27
Answering to dbenham, I have no way to know if it was a coding error or an intended feature, but this is how the process works
The lines in batch file are processed inside the inner BatLoop function when a batch "context" is created. This function receives, as one of its arguments, a pointer to the command that caused the "context" to be created.
Inside this function the commands in the batch file are iterated. The loop that iterates over the commands makes a test in each iteration: if extensions are enabled, it is the first line in the batch file and the arguments of the command that started the context starts with a colon (a label), a goto is generated to jump to the label.
Up to here, I have to suppose that this is the intended behaviour to handle the call :label syntax: create a new "context", load the file, jump to the label.
But the command argument received is never changed, a different variable is used to track the execution of the commands in the batch file. If a new batch file is loaded into / overwrites the current batch "context" (we have not used call command), after loading the new batch code, BatLoop resets the line count (we start at the first line of the loaded file) and, voila, the condition at the start of the loop (extensions enabled, first line, the colon) is true again (the pointed input command has not been changed) and a new goto is generated.
To comment a bit more, here is the code I came out reading the answer. It basically give you a 'utility' file where you can add your sub/fnc in a common library for code maintenance.
A) As a example, here is the 'utility_sub.cmd' file:
REM ==============================================
REM CALL THE SELECTED SUB
REM ==============================================
REM echo %~1
GOTO :%~1
REM ==============================================
REM ERROR MANAGEMENT
REM ==============================================
REM Ref : https://ss64.com/nt/exit.html
:RAISE_ERROR
EXIT /B 1
:RESET_ERROR
EXIT /B 0
REM Demo call
REM =========
REM CALL :RAISE_ERROR
REM echo RAISE_ERROR ERRORLEVEL = %ERRORLEVEL%
REM If %ERRORLEVEL% GTR 0 (
REM set msg="%tab%- Error detected ..."
REM CALL :SUB_STDOUT_MSG !msg!, 1
REM )
REM CALL :RESET_ERROR
REM echo RESET_ERROR ERRORLEVEL = %ERRORLEVEL%
REM ==============================================
REM SUB_STDOUT_MSG
REM ==============================================
:SUB_STDOUT_MSG
REM CALL :SUB_STDOUT_MSG "%param1%", %param2%, %param3%
REM Instead of this stdout sub, we can use Unix 'tee.exe'
REM but there is no 'line counter' feature like this sub
REM Call example :
REM EDI_Generate_Stat_Csv | tee c:\temp\voir.txt
REM Def :
REM Capture output from a program and also display the output to the screen, at the same time.
REM %~1 => Expand %1 removing any surrounding quotes (")
set msg=%~2
set sendtoLog=%3
set addCounter=%4
If !msg!==. (
REM Write empty line
echo!msg!
If !sendtoLog! EQU 1 (
echo!msg! >> %log_file%
)
) else (
REM (a) Write comment line (b) add counter if any
If !addCounter! EQU 1 (
set /a msgCounter+=1
set msg=!msgCounter! - !msg!
REM Pad counter left for single digit
If !msgCounter! LSS 10 (
set msg=0!msg!
)
)
REM Output to console
echo !msg!
REM Output to log
If !sendtoLog! EQU 1 (
echo !msg! >> %log_file%
)
)
EXIT /B
B) And here is how to call the 'SUB_STDOUT_MSG' in you 'main-logic' command file:
REM ... some other code here
REM ==============================================
REM PROGRAM END
REM ==============================================
set msg=.
CALL :SUB_STDOUT_MSG !msg!, 1
set msg="My programA - End"
CALL :SUB_STDOUT_MSG !msg!, 1
set msg="%date:~0,4%-%date:~5,2%-%date:~8,2% %time:~0,2%:%time:~3,2%:%time:~6,2%"
CALL :SUB_STDOUT_MSG !msg!, 1
set msg="+++++++++++++++"
CALL :SUB_STDOUT_MSG !msg!, 1
timeout 2 > Nul
REM Skip all SUB ROUTINE
GOTO :EOF
REM ==============================================
REM CALL SUB ROUTINE
REM ==============================================
:SUB_STDOUT_MSG
REM echo calling sub %0
CALL "C:\Utilitaires\Financement\Utility_Sub.cmd" SUB_STDOUT_MSG %*
EXIT /B
:EOF
What about providing the target label as the first agrument of the called script? You needed to modify the called dscript then though.
file1.bat (main):
#echo off
echo/
echo File "%~0": call "file2.bat" [no arguments]
call "file2.bat"
echo/
echo File "%~0": call "file2.bat" :DEMO
call "file2.bat" :DEMO
echo/
echo File "%~0": call "file2.bat" :DEMO A B C
call "file2.bat" :DEMO A B C
file2.bat (sub):
#echo off
set "ARG1=%~1" & if not defined ARG1 goto :TEST
if "%ARG1:~,1%"==":" goto %ARG1%
:TEST
echo File "%~nx0", :TEST; arguments: %*
goto :EOF
:DEMO
echo File "%~nx0", :DEMO; arguments: %*
echo before `shift /1`:
echo "%%~0" refers to "%~0"
echo "%%~1" refers to "%~1"
shift /1
echo after `shift /1`:
echo "%%~0" refers to "%~0"
echo "%%~1" refers to "%~1"
goto :EOF
Output:
>>> file1.bat
File "file1.bat": call "file2.bat" [no arguments]
File "file2.bat", :TEST; arguments:
File "file1.bat": call "file2.bat" :DEMO
File "file2.bat", :DEMO; arguments: :DEMO
before `shift /1`:
"%~0" refers to "file2.bat"
"%~1" refers to ":DEMO"
after `shift /1`:
"%~0" refers to "file2.bat"
"%~1" refers to ""
File "file1.bat": call "file2.bat" :DEMO A B C
File "file2.bat", :DEMO; arguments: :DEMO A B C
before `shift /1`:
"%~0" refers to "file2.bat"
"%~1" refers to ":DEMO"
after `shift /1`:
"%~0" refers to "file2.bat"
"%~1" refers to "A"

Show help message if any command line argument equals /?

I wish to write a Windows Batch script that first tests to see if any of the command line arguments are equal to /?. If so, it displays the help message and terminates, otherwise it executes the rest of the script code. I have tried the following:
#echo off
FOR %%A IN (%*) DO (
IF "%%A" == "/?" (
ECHO This is the help message
GOTO:EOF
)
)
ECHO This is the rest of the script
This doesn't seem to work. If I change the script to:
#echo off
FOR %%A IN (%*) DO (
ECHO %%A
)
ECHO This is the rest of the script
and call it as testif.bat arg1 /? arg2 I get the following output:
arg1
arg2
This is the rest of the script
The FOR loop appears be ignoring the /? argument. Can anyone suggest an approach to this problem that works?
Something like this should do the trick:
#echo off
IF [%1]==[/?] GOTO :help
echo %* |find "/?" > nul
IF errorlevel 1 GOTO :main
:help
ECHO You need help my friend
GOTO :end
:main
ECHO Lets do some work
:end
Thanks to #jeb for pointing out the error if only /? arg provided
Do not use a FOR loop, but use the following instead:
#ECHO OFF
:Loop
IF "%1"=="" GOTO Continue
IF "%1" == "/?" (
ECHO This is the help message
GOTO:EOF
)
SHIFT
GOTO Loop
:Continue
ECHO This is the rest of the script
:EOF

Resources