Reputation: 161
Okay, I want a batch file to detect whether if it can find the file it is inhabiting and not anything else.
For Example: I receive the path, (Down there) from the variable %~dp1.
C:\Users\%USERNAME%\Desktop\File\file1.bat
But what I want to do is receive this section of its directory, "\File\", and check whether the batch file can find out if that directory really exists.
Upvotes: 1
Views: 317
Reputation: 342
This will return the dir name (without path) of the running batch file:
@echo off
for %%a in ("%~dp0\.") do echo %%~nxa
Magoo has it slightly wrong: . not ..
An alternative if you don't use blanks in filenames/dirs is:
@echo off
set p=%~p0
for %%x in (%p:\= %) do set dir=%%x
echo %dir%
Upvotes: 0
Reputation: 7163
Here is a solution, did not code solution for file being in root.
Variable f
is what I believe you are asking for.
foo.cmd
@echo off
setlocal
::: p parent
::: g grandparent
::: a grandparent absolute
::: f folder of this batch file
set p=%~dp0
set g=%~dp0\..
FOR /F "delims=" %%t IN ("%g%") DO SET "a=%%~ft"
call set f=%%p:%a%=%%
call set f=%%f:\=%%
echo p is: %p%
echo g is: %g%
echo a is: %a%
echo f is: %f%
endlocal
Test Cases
L:\test>foo.cmd
p is: L:\test\
g is: L:\test\\..
a is: L:\
f is: test
L:\test>md subdir
L:\test>cd subdir
L:\test\subdir>..\foo.cmd
p is: L:\test\
g is: L:\test\\..
a is: L:\
f is: test
L:\test\subdir>copy ..\foo.cmd
1 file(s) copied.
L:\test\subdir>foo.cmd
p is: L:\test\subdir\
g is: L:\test\subdir\\..
a is: L:\test
f is: subdir
L:\test\subdir>cd..
L:\test>cd..
L:\>copy test\foo.cmd
1 file(s) copied.
L:\>foo.cmd
p is: L:\
g is: L:\\..
a is: L:\
f is: \=
Upvotes: 0
Reputation: 80023
for %%a in ("%~dp0\..") do SET "parent=%%~nxa"
ECHO(%parent%
since we are aware that we're running from a directory that probably has a parent, this sets parent
to nothing if the parent is the root or the batch is at the root.
Upvotes: 2
Reputation: 14290
Getting the parent directory of the batch file. I know we covered this several times on SO but I can't find the question.
for %%a in ("%~dp0\.") do for %%b in ("%%~dpa\.") do echo %%~nxb
Upvotes: 0