3

This is a very specific question, however;

Say I have a batch file running from\located in the directory c:\data\src\branch_1

How do I set my environment variable %buildpath% to c:\build\bin\branch_1 in a batch file?

(To be extra clear, if the same batch file is located in c:\foo\bar\branch_2 I want it to set %buildpath% to c:\build\bin\branch_2)

2 Answers 2

6

You should be able to use the environment variable %~dp0 to get you the drive and path of the batch file currently running. From there, it's a not-very-efficient method of stripping off the end of that string character by character and building a new string.

For example, the batch file:

@setlocal enableextensions enabledelayedexpansion
@echo off
set olddir=%~dp0
echo Current directory is: !olddir!
if "!olddir:~-1!" == "\" (
    set olddir=!olddir:~0,-1!
)
set lastbit=
:loop
if not "!olddir:~-1!" == "\" (
    set lastbit=!olddir:~-1!!lastbit!
    set olddir=!olddir:~0,-1!
    goto :loop
)
set newdir=c:\build\bin\!lastbit!
echo New directory is: !newdir!
endlocal

running as c:\data\src\branch1\qq.cmd returns the following:

Current directory is: C:\data\src\branch1\
New directory is: c:\build\bin\branch1

As to how it works, you can use !xyz:~n,m! for doing a substring of an environment variable, and negative m or n means from the end rather than the beginning. So the first if block strips off the trailing \ if it's there.

The loop is similar but it transfers characters from the end of the path to a new variable, up until the point where you find the \. So then you have the last bit of the path, and it's a simple matter to append that to your fixed new path.

Sign up to request clarification or add additional context in comments.

3 Comments

Nice, was just looking at this and using for on %0 with %~di%~pi :P
Thanks, but, that was the easy part. The hard part is to find the last \ and substring from there :/
Sorry, @Viktor, I should have read the question a little more closely. Updated my answer to meet the actual specs rather than what I thought they were :-)
1

Old case, but still...

easy way of setting current directory into variable.

@echo off
cd > dir.tmp
set /p directory= <dir.tmp
echo %directory%    <-- do whatever you want to the variable. I just did a echo..
del dir.tmp > nul

1 Comment

If you only need the current directory, you can set directory=%CD% However, @ViktorSehr asked for the directory that the batch file exists in as a file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.