20

I have a batch files that calls other batch files like this:

e:\foo\master.bat has the content:

call e:\bar\run1.bat 

and e:\bar\run1.bat has the content

app1.exe

the problem is that when I run the master.bat app1.exe will not be executed, because it will expect it to be in the e:\foo directory instead of it being in e:\bar directory

Colyn1337
  • 2,457
  • 2
  • 25
  • 40
Omu
  • 357

3 Answers3

19

You are a bit unclear where app1.exe is located.

If it shares the folder with run1.bat change run1.bat

to either

@Echo off
Pushd "%~dp0"
app1.exe
popd

or

@Echo off
"%~dp0app1.exe"

%0 refers to the currently running batch and the modifier ~dp returns drive and path (with a trailing backslash.)

LotPings
  • 1,063
4

The answer to your question can be drawn from a similar question on Stack Overflow.

What is the current directory in a batch file?

Using the variables mentioned here, you can update run1.bat to call app1.exe with the following line: %~dp0app1.exe. (The %~dp0 variable includes a trailing slash.) This will tell the batch file to run the executable from the current batch file's location.

Sam Erde
  • 3,549
0

You can use my universal script for executing a command in a specified working directory:

CALL :EXEC_IN e:\bar run1.bat

The EXEC_IN batch-function is:

@ECHO OFF
:: Execute a program inside a specified working directory
:: 1. Working directory
:: 2. Full file name
:: 3+ Arguments
:EXEC_IN
SETLOCAL

:: Scan fixed positional arguments: SET WD=%1&SHIFT SET FL=%1&SHIFT

:: Collect all arguments into %ALL%: :EI_AA_START IF [%1]==[] GOTO EI_AA_END SET ALL=%ALL%%SEP%%1 SET SEP= SHIFT GOTO :EI_AA_START :EI_AA_END

:: Execute command %FL% in directory %WD% with args %ALL%: PUSHD %WD% CALL %FL% %ALL% POPD ENDLOCAL EXIT /B

If desired, feel free to modify it to take the working directory from the file path intead of passing it as the first argument:

CALL :EXEC_IN_F e:\bar\run1.bat

This modified script is:

:: Execute a program with its location as working directory:
:: 1. Full path to the executable
:: 2+ Arguments
:EXEC_IN_F
SETLOCAL

:: Scan fixed positional arguments: SET FL=%1 SET WD=%~p1 SHIFT

:: Collect all arguments into %ALL%: :EI_AA_START IF [%1]==[] GOTO EI_AA_END SET ALL=%ALL%%SEP%%1 SET SEP= SHIFT GOTO :EI_AA_START :EI_AA_END

:: Execute command %FL% in directory %WD% with args %ALL%: PUSHD %WD% CALL %FL% %ALL% POPD ENDLOCAL EXIT /B