2

Suppose my directory structure is ..

C:\Program Files\abc\myscript.bat

so from myscript.bat i want to get the parent name of this script which is abc in this case.

Please note that I don't want complete path of parent, i want only parent name like abc.

what is the simple way to achieve this?

amuser
  • 781
  • 2
  • 6
  • 11
  • 2
    possible duplicate of [Get parent directory name for a particular file using DOS Batch scripting](http://stackoverflow.com/questions/2396003/get-parent-directory-name-for-a-particular-file-using-dos-batch-scripting) – wOxxOm Sep 06 '15 at 11:44
  • all you need is `echo %~dp0` – npocmaka Sep 06 '15 at 11:58
  • 1
    `set "p=%~P0"` and `for %%a in ("%p:~,-1%") do echo %%~Na` – Aacini Sep 06 '15 at 12:03

1 Answers1

5

Probably the simplest code could be

for %%a in ("%~p0.") do echo(%%~nxa

But this code has a point of failure, since you have not defined what to do when the batch file is located at the root of a drive, that is, what to do when the folder containing the batch file does not have a name.

MC ND
  • 69,615
  • 8
  • 84
  • 126
  • 1
    +1 `for %%a in ("%~p0.") do echo "%%~nxa"`. Then, `D:\bat\SO\32423120.bat` returns `"SO"` and `D:\bat\32423120.bat` returns `"bat"` and `D:\32423120.bat` returns `""`. Works perfectly, no point of failure! – JosefZ Sep 06 '15 at 14:22
  • 2
    @JosefZ, yes, the code is technically correct and as you indicate it doesn't fail, but if the OP has code that rely on my code assuming it will return a string with the name of the folder, but what is returned is an empty string, the OP code could fail. It is necessary to clearly define how the code should behave. Without this definition, all I can do is warn. – MC ND Sep 06 '15 at 15:29
  • @JosefZ in a nutshell, what would the script return if located at `C:\ ` or `\\myserver\myshare`? – John Castleman Sep 06 '15 at 17:17
  • @JohnCastleman Let's consider there is no difference: `C:\32423120.bat` and `D:\32423120.bat` should return the same zero length string (but I won't make my `%SystemDrive%` root dirty to check it). **Interesting**: `\\myserver\myshare\32423120.bat` returns `myshare` while `\\myserver\D$\32423120.bat` returns `D$`. _Imho_, better practice for `UNC` paths could be `pushd \\myserver\myshare` (or `pushd \\myserver\D$`) and then use `%__cd__%32423120.bat` – JosefZ Sep 06 '15 at 20:56