Considerations in calling .bat files from .bat files

Posted in software by Christopher R. Wirz on Sun Aug 03 2008



.bat (short for batch) files offer a lot of automation - especially for applications which do not offer a user interface. These scripts can issue argments to programs (such as install executables), sent environment variables, and even run other bat files. I like to use bat files to clean temp files at startup.

Note: The word rem followed by a space will not execute that line. It is basically a comment. These won'd display if '@echo off' is called.

When running bat files from within a bat file, it is important to set the present working directory (pwd) to that of the script. This helps prevent you from accidentally modifying other parts of the system. After you have called other bat files (which may change changed the pwd), it is important to set the pwd again.

The command to do this is 'cd /d %~dp0', but let's see how it's used in context.


rem Prevent displaying of future rem lines
@echo off

rem Clear the screen
cls

echo Say something to the console

rem Set the current directory as present working directory
cd /d %~dp0

rem Call another bat file
call other_bat_file.bat

rem Set the current directory as present working directory
rem The other_bat_file may have changed it
cd /d %~dp0

rem Call another bat file (that has file spaces)
call "other bat file.bat"

rem Set the current directory as present working directory
rem The other bat file may have changed it
cd /d %~dp0

rem Pipe the output of a bat file to a txt file
call bat_file_with_reporting.bat > out.txt

rem Set the current directory as present working directory
rem The other bat file may have changed it
cd /d %~dp0

Looking for a job?