batch script to set a variable with the current path location
WindowsBatch FileCmdWindows Problem Overview
How can I set a variable with the current location? For instance, if I get in c:\test
and want to set the variable to test
and if I get inside c:\test\test2
the variable will be set to test2
.
I'm thinking about using a for
to get inside a lot of folders and check if some file exists, if the correct file exist I want to set the current folder to a variable so I can copy the path and copy the folder.
The main problem deals with copying the rest of the files is the same folder as the .inf file.
Windows Solutions
Solution 1 - Windows
The current directory is in the "shadow" variable cd.
You could try
set "var=%cd%"
Solution 2 - Windows
%~dp0
This expands into the drive & path of the currently running batch file. I usually surround my batch files with something like:
@echo off
pushd %~dp0
...
popd
Edit: It seems I didn't understand the OP. My example gets the location of the currently running script, not the "Current Directory". +1 to jeb.
Solution 3 - Windows
I think there is a little confussion here. %CD% always have the current directory, so you don't need to add anything to have it. However, by rereading your original question, I think that you need the LAST PART of the current directory, that is, the name of the current location excluding all previous locations. If so, then you may use this:
set i=0
:nextdir
set /a i+=1
for /f "tokens=%i% delims=\" %%a in ("%CD%") do if not "%%a" == "" set lastdir=%%a& goto nextdir
echo Current location: %lastdir%