Graham
Graham

Reputation: 8141

How to get the drive letter of the calling batch when the called batch is on a different drive

I have two windows batch files: a.bat and b.bat.

b.bat is on the D: drive and is in my path

a.bat is on the E: drive and has something like the following in it:

call b.bat
echo %thedrive%

b.bat has something like the following in it:

IF %~d0==D: (
  SET %thedrive=testdrive
) ELSE (
  SET %thedrive=livedrive
)

The problem is that %~d0 is getting the drive letter that b.bat is on and not the drive that the calling (a.bat) batch file is on.

How do I get the drive the calling batch file is on?

Upvotes: 2

Views: 51

Answers (2)

Scott C
Scott C

Reputation: 1660

Because b.bat is in the path, you can just check what the current directory is in b.bat. That is, b.bat should be:

IF %cd:~0,2% == D: (
  SET thedrive=testdrive
) ELSE (
  SET thedrive=livedrive
)

Upvotes: 1

dbenham
dbenham

Reputation: 130809

b.bat has no way of knowing that it was CALLed from within another batch file, let alone where said calling batch file is located. The only way b.bat could know is if the information is passed in as an argument, and then you would be relying on the caller to pass the information.

Based on the code you posted, it seems you want a.bat to know what drive it is on. If so, you will need to move the code from b.bat to a.bat.

If you have many .bat scripts that need to set the thedrive variable, and you don't want to include all the logic in all the files, then I would change b.bat as follows:

IF /i %~d1==D: (
  SET thedrive=testdrive
) ELSE (
  SET thedrive=livedrive
)

And each of your a.bat scripts would have to call b.bat using:

call b.bat "%~f0"

Upvotes: 1

Related Questions