The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,779 other followers

Batch file to get parent directory (not the directory of the batch file, but the parent of that directory)

Posted by jpluimers on 2011/08/30

The problem solved here is two-fold:

  1. The ~dp syntax for getting the directory/path part only works for parameters and loop indexes, not on variables.
    You can work around this by having a 1-iteration for-loop.
  2. The :~ syntax for getting the substring works only for variables, not for parameters and loop indexes.
    You can work around this by assigning to a temporary variable.

Example:

  echo batchfile=%0
  echo full=%~f0
setlocal
::http://stackoverflow.com/questions/636381/what-is-the-best-way-to-do-a-substring-in-a-batch-file
  set Directory=%~dp0
echo Directory=%Directory%
:: strip trailing backslash
  set Directory=%Directory:~0,-1%
echo %Directory%
::  ~dp does not work for regular environment variables:
::  set ParentDirectory=%Directory:~dp%  set ParentDirectory=%Directory:~dp%
::  ~dp only works for batch file parameters and loop indexes
  for %%d in (%Directory%) do set ParentDirectory=%%~dpd
  echo ParentDirectory=%ParentDirectory%
endlocal

This will show:

  1. The directory of the batch file
  2. The directory but without the trailing backslash
  3. The parent directory of the batch file

Hope you can give this some use.

–jeroen

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

 
%d bloggers like this: