Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subroutines in batch files

Tags:

batch-file

Given the following code:

@Echo off ECHO Start ECHO Calling SUB_A CALL :SUB_A ECHO Calling SUB_B CALL :SUB_B  :SUB_A     ECHO In SUB_A     GOTO:EOF  :SUB_B     ECHO In SUB_B     GOTO:EOF  ECHO End 

I expect this output:

Start Calling SUB_A In SUB_A Calling SUB_B In SUB_B End 

But I get this:

Start Calling SUB_A In SUB_A Calling SUB_B In SUB_B In SUB_A 

What am I doing wrong here?

like image 649
Michael Avatar asked Sep 14 '10 23:09

Michael


People also ask

What is %% in a batch file?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

What does %1 do in batch?

When used in a command line, script, or batch file, %1 is used to represent a variable or matched string. For example, in a Microsoft batch file, %1 can print what is entered after the batch file name.


2 Answers

If you want to return from a CALL, you use EXIT command with /B argument (as "EXIT" alone will terminate the batch file).

For example:

CALL :SUB_ONE CALL :SUB_TWO  GOTO :EOF  :SUB_ONE ECHO Hello from one EXIT /B  :SUB_TWO ECHO Hello from two EXIT /B  :EOF 
like image 141
aikeru Avatar answered Oct 07 '22 10:10

aikeru


The line CALL :SUB_B returns, the script proceeds to the next few lines:

:SUB_A           # no effect from this one ECHO In SUB_A    # prints message 

You need to insert a GOTO:EOF after the call if you want it to stop there.

Batch files are not structured programs; they are a sequence of instructions with some BASIC-like facility for GOTO and CALL.

like image 29
Edmund Avatar answered Oct 07 '22 08:10

Edmund