Reputation: 4929
How can I store a directory name in a variable inside batch file??
Upvotes: 0
Views: 2044
Reputation: 29689
To allow a script to determine its parent folder directory name:
@echo off
::setlocal enableextensions,enabledelayedexpansion
SET CDIR=%~p0
SET CDIR=%CDIR:\= %
FOR %%a IN (%CDIR%) DO (
SET CNAME=%%a
)
echo %CDIR%
echo %CNAME%
pause
Or, better yet:
@echo off
::setlocal enableextensions,enabledelayedexpansion
SET CDIR=%~p0
SET CDIR=%CDIR:~1,-1%
SET CDIR=%CDIR:\=,%
SET CDIR=%CDIR: =_%
FOR %%a IN (%CDIR%) DO SET "CNAME=%%a"
echo %CDIR%
SET CNAME=%CNAME:_= %
echo %CNAME%
pause
Upvotes: 0
Reputation: 405
Use the set command.
Example:
rem Assign the folder "C:\Folder1\Folder2" to the variable "MySavedFolder"
set MySavedFolder=C:\Folder1\Folder2
rem Run the program "MyProgram.exe" that is located in Folder2
%MySavedFolder%\MyProgram.exe
rem Run the program "My Second Program.exe" that is located in Folder 2 (note spaces in filename)
"%MySavedFolder%\My Second Program.exe"
rem Quotes are required to stop the spaces from being command-line delimiters, but the command interpreter (cmd.exe) will still substitute the value of the variable.
To remove the variable, assign nothing to the name:
set MySavedFolder=
Since you are inside a batch file, I suggest surrounding your variable usage with setlocal and endlocal at the end of the file; this makes your environment variables local to the batch file and doesn't pollute the global environment namespace.
Upvotes: 0
Reputation: 111336
set dirname=c:/some/folder
echo %dirname%
REM retrieve the last letter of the folder
REM and save it in another variable
set lastLetter=%dirname:~-1%
echo %lastLetter%
Upvotes: 2
Reputation: 2265
Without more precisions it's difficult to help you...
Maybe you want the current directory?
set name=%CD%
echo %name%
Upvotes: 0
Reputation: 1754
To return the directory where the batch file is stored use %~dp0
%0 is the full path of the batch file,
set src= %~dp0
echo %src%
I've used this one when I expect certain files relative to my batch file.
Upvotes: 0