basickarl
basickarl

Reputation: 40561

Get absolute path via CMD script of directory

script-being-invoked.cmd:

REM This is my script file, it is being invoked from anywhere
REM Get absolute path to root directory
set astr=%~dp0
set substr1=\mq_1.7.6\interface\
set substr2=\
call set rootPath=%%astr:%substr1%=%substr2%%%

I'm trying to get the absolute directory path a few paths below from the file being invoked in the interface directory. The issue however is that the path in the code above changes. The version in mq_1.7.6 could change. Is there anyway to get this value via cmd scripting? I would have done \..\.. but this doesn't seem to work in Windows.

Upvotes: 0

Views: 165

Answers (3)

user7818749
user7818749

Reputation:

Here's one method:

@pushd "%~dp0..\"
@echo %cd%
@popd

shorter one line:

@pushd "%~dp0..\" && echo %cd% && popd

Upvotes: 0

Compo
Compo

Reputation: 38719

It appears from your question, that you're trying to retrieve the name of the scripts grandparent, in this case mq_1.7.6.

It is still a little unclear however, whether you want that in isolation, i.e. mq_1.7.6, or as an absolute path, e.g. P:\ath\to\mq_1.7.6


If the former is your intention then the following should suffice:

@For %%A In ("%~f0\..\..")Do @Echo(%%~nxA

If you need that as a variable then:

@For %%A In ("%~f0\..\..")Do @Set "Gp=%%~nxA"

If you're just trying to capture the version string from mq_1.7.6, in this case 1.7.6, then a simple additional line may be all that is required:

@For %%A In ("%~f0\..\..")Do @Set "Gp=%%~nxA"
@Set "Gp=%Gp:*_=%"


If on the other hand you wanted the latter, i.e. the absolute path of the scripts grandparent, the the only real difference is in the metavariable expansion:

@For %%A In ("%~f0\..\..")Do @Echo(%%~fA

If you need that as a variable then:

@For %%A In ("%~f0\..\..")Do @Set "Gp=%%~fA"


If neither of my interpretations of your intent are correct, can you please provide an example of what you wanting to be returned, and whether you want that simply printing to the console, or saving as a variable etc.

Upvotes: 0

user330315
user330315

Reputation:

I usually do that using the ~fi expansion pattern. Unfortunately this can only be used (at least to my knowledge) in a for loop.

set "parentdir=%~dp0.."
for %%i in ("%parentdir%") do set "realparent=%%~fi"
echo "%parentdir%"
echo "%realparent%"

If the above is in a batch file located in c:\foo\bar\mq_1.7.6\interface the variable realparent will contain c:\foo\bar\mq_1.7.6 and parentdir would contain c:\foo\bar\mq_1.7.6\interface\...

So the for loop essentially turns a relative path into an absolute path.

Upvotes: 1

Related Questions