Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get windows batch's parent folder

I'm writing a batch file, I need to get the parent folder of this bat file. Is it possibile? NB I mean the parent folder of the batch file not of the current directory of the prompt calling that batch.

Thanks

like image 311
Tobia Avatar asked May 18 '13 11:05

Tobia


People also ask

How do I go back a parent directory in CMD?

When you want to go back, type cd - and you will be back where you started.

What is Windows parent folder?

With a directory, a parent directory is a directory containing the current directory. For example, in the MS-DOS path below, the "Windows" directory is the parent directory of the "System32" directory, and C:\ is the root directory.

How do I create a parent folder in Windows?

If you want to open the file/folder in a new window use CTRL+Click. On the contrary, the "Up" button used to take you one level higher (to the parent) regardless of the means you used to get to that folder (search results, shortcuts, etc.).


3 Answers

The parent folder of a Batch is in the Variable %~dp0 located. Example:

@echo off&setlocal
for %%i in ("%~dp0.") do set "folder=%%~fi"
echo %folder%
like image 69
Endoro Avatar answered Oct 12 '22 09:10

Endoro


Endoro's answer doesn't work for me either but this does. This is what I use myself to do this.

V3

One of these should do the right thing

for %%I in ("%~dp0.") do for %%J in ("%%~dpI.") do set ParentFolderName=%%~nxJ
echo %ParentFolderName%

for %%I in ("%~dp0.") do for %%J in ("%%~dpI.") do set ParentFolderName=%%~dpnxJ
echo %ParentFolderName%

V2:

for %%I in ("%~dp0\.") do set ParentFolderName=%%~nxI
echo %ParentFolderName%

V1:

This one gets the parent directory of the current working directory

for %%I in (..) do set ParentFolderName=%%~nI%%~xI
echo %ParentFolderName%

Reference: For | Microsoft Docs

like image 34
cpcolella Avatar answered Oct 12 '22 11:10

cpcolella


If you want the folder where the batch file is located, you can assign

SET folder=%~dp0

as mentioned in another answer.

If you want the folder above the location of the batch file, you can assign

SET folder=%~dp0..\

However, this last variable could be inadequate if you plan to show the path to the user. In that case, perphaps it is preferable

FOR %%A IN ("%~dp0.") DO SET folder=%%~dpA

As an example, if you have the following script in C:\Users\Public

@ECHO OFF
ECHO %~dp0
ECHO %~dp0..\
FOR %%A IN ("%~dp0.") DO ECHO %%~dpA

the output will be

C:\Users\Public\
C:\Users\Public\..\
C:\Users\
like image 37
ASdeL Avatar answered Oct 12 '22 11:10

ASdeL