Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a .BAT file from another .bat file

Tags:

batch-file

I have a .bat file to which I can pass parameters.

LOAD_TABLE_WRAPPER.BAT Table1 DEV

Briefly, it runs an SQL to load Table1 on the Dev environment. Now, I want it to load multiple tables overnight. So, I set up a master .BAT which goes something like

::MASTER_LOAD.BAT
CALL LOAD_TABLE_WRAPPER.BAT Table1 Dev
CALL LOAD_TABLE_WRAPPER.BAT Table2 Dev
CALL LOAD_TABLE_WRAPPER.BAT Table3 Dev

If I submit MASTER_LOAD.BAT from cmd, it executes the load for Table1 but does not proceed to Table2 load. These are the last two lines of the WRAPPER.BAT

:eof
exit %ERROR_STATUS%
like image 567
Amol Vashistha Avatar asked Aug 03 '12 16:08

Amol Vashistha


People also ask

How do I echo a batch file?

To display the command prompt, type echo on. If used in a batch file, echo on and echo off don't affect the setting at the command prompt. To prevent echoing a particular command in a batch file, insert an @ sign in front of the command.


1 Answers

Your exit %error_status% command in LOAD_TABLE_WRAPPER.BAT is terminating your batch session, so your MASTER_LOAD.BAT never gets a chance to resume with the next call.

You can fix the problem simply by adding the /B option to your EXIT command

exit /b %error_stats%

I almost never use EXIT without /B in a batch file (though there are times when /B is not wanted).

But another alternative is to run the called scripts via CMD instead of CALL.

::MASTER_LOAD.BAT
CMD /C LOAD_TABLE_WRAPPER.BAT Table1 Dev
CMD /C LOAD_TABLE_WRAPPER.BAT Table2 Dev
CMD /C LOAD_TABLE_WRAPPER.BAT Table3 Dev

There are a number of differences between the methods

CALL with EXIT /B

  • Comparatively fast
  • Can preserve environment variable values upon return (SETLOCAL is available if you don't want to preserve values)
  • Called script inherits delayed expansion and extension states (enabled or disabled)

CMD /C

  • Comparatively slow
  • Cannot preserve environment variable values upon return. (You could write out the definitions to a file and load them back in upon returning to the master, but that is not convenient or efficient)
  • Called script always starts with default delayed expansion and extension states (Normally delayed expansion is disabled and extensions are enabled)

I would never recommend using CMD /C over CALL unless the called batch files have EXIT without the /B option and you cannot modify the batch file to add the /B option.

like image 85
dbenham Avatar answered Sep 23 '22 10:09

dbenham