Reputation: 40561
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
Reputation:
Here's one method:
@pushd "%~dp0..\"
@echo %cd%
@popd
shorter one line:
@pushd "%~dp0..\" && echo %cd% && popd
Upvotes: 0
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
@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:*_=%"
@For %%A In ("%~f0\..\..")Do @Echo(%%~fA
If you need that as a variable then:
@For %%A In ("%~f0\..\..")Do @Set "Gp=%%~fA"
Upvotes: 0
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