ENDLOCAL

End localisation of environment changes in a batch file. Pass variables from one batch file to another.

Syntax
      ENDLOCAL

If SETLOCAL is used to make variables 'local' to one batch script, then those variables will be invisible to all other batch scripts unless explicitly passed using an ENDLOCAL & SET... command.

If SETLOCAL is used without a corresponding ENDLOCAL then local environment variables will be discarded when the batch file ends. Ending the cmd.exe session will discard all Environment Variables both local and global.

Passing variables from one routine to another

The CMD command processor always works on a line-by-line basis, so it will convert all %variables% into their text values before executing any of the commands.

By putting ENDLOCAL & SET commands on a single line you are able to SET a variable just before the localisation is ended by the ENDLOCAL command.


Examples:

::Sales.cmd
   
   @Echo off
   SETLOCAL
      Set _item="Ice Cream Maker"
      Set _price=450
   ENDLOCAL & SET _return1=%_item%& SET _return2=%_price%

::Results.cmd

   @Echo off
   SETLOCAL
   CALL Sales.cmd
   Echo [%_return1%] will cost [%_return2%]


::SubDemo.cmd
   
   @Echo off
   SETLOCAL
   CALL sub_products
   Echo [%_return1%] will cost [%_return2%]

   :sub_products
   SETLOCAL
      Set _item="Coffee Grinder"
      Set _price=150
   ENDLOCAL & SET _return1=%_item%& SET _return2=%_price%

Multiple SET commands may be added to pass multiple variables, just prefix each with an &
Be aware that any trailing spaces    will be added to the variables value.

Improving readability

The 'ENDLOCAL & SET' technique described above can become difficult to read if you have a lot of SET commands all on the same line. This can be made easier to read if you first store all the Set assignments in a single variable (_returns) as shown below (thanks to Ilya Bobyr for this technique)

Set _returns=^
  Set _return1=%_item%^&^
  Set _return2=%_price%^&^
  Set _return3=%_discount%^&^
  Set _return4=%_delivery%

Endlocal & %_returns%

In these examples we have used the variable names _return1, _return2 etc, but you can use any names for the return variables, even re-use the exact same variable name inside and outside the ENDLOCAL command (SET _price=%_price%)

"A good place to visit, but a poor place to stay" - Josh Billings

Related:

SETLOCAL - Begin localisation of environment variables in a batch file.
Equivalent bash command (Linux): readonly - Mark variables/functions as readonly



Back to the Top

© Copyright SS64.com 1999-2012
Some rights reserved