19

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

3 Answers 3

18

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.)

2
  • the Pushd method works best for me because, app1.exe internally also uses current dir, and using Pushd it will use the dir where app1.exe is located, without Pushd (but with the prefix) it will use the master.bat location
    – Omu
    Commented May 31, 2018 at 18:18
  • 1
    With this type of implications in mind, that method was the first in my answer intentionally. Thanks for feedback.
    – LotPings
    Commented May 31, 2018 at 18:22
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.

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .