views:

36

answers:

2

I am trying to write a batch file that exists in an arbitrary directory and will create a new directory two levels above it. For instance, the batch file here:

w:\src\project\scripts\setup.bat

would create:

w:\src\project.build

I can't seem to figure out how to expand a path. Here is what I am currently doing:

@set SCRIPT_DIR=%~dp0
@set ROOT_DIR=%SCRIPT_DIR%\..
echo ROOT DIR:  %ROOT_DIR%
@set ROOT_DIR_NAME=%ROOT_DIR:~0,-1%
@echo ROOT DIR NAME: %ROOT_DIR_NAME%

And this produces:

ROOT DIR:  w:\src\w_dev1\scripts\\..
ROOT DIR NAME: w:\src\w_dev1\scripts\\.

What I wanted to do, was get ROOT_DIR_NAME to be the directory itself (without the trailing slash). I know I could hack this and switch the -1 to account for the '..', but is there not a cleaner way to handle this?

+1  A: 

Your line @set ROOT_DIR_NAME=%ROOT_DIR:~0,-1% removes ony 1 character from the variable value. You want to remove more ('scripts' has 7, plus you have these '\..' at the end...). Are you sure that you always have 'scripts' as the last directory in the path where you install?

Anyway, if you use @set ROOT_DIR_NAME=%ROOT_DIR:~0,-11% it should work for your particular example.

However, I would suggest you use a more generic approach:

@set SCRIPT_DIR=%~dp0
@pushd %script_dir%
@pushd ..\..
@echo. current directory now is %cd%
@set root_dir=%cd%
@popd
@popd

This works independently of the length of your directory names.

The pushd commands change directories (and remember where it came from) -- the popd commands go back to what was remembered by pushd. The %cd% variable holds the current drive+path.

pipitas
A: 

You can use the for command to resolve a relative path into a canonical absolute path:

@echo off
set "SCRIPT_DIR=%~dp0"
for %%P in ("%SCRIPT_DIR%..\..") do set "ROOT_DIR_NAME=%%~fP"

This script will set ROOT_DIR_NAME to the grand parent directory of the script.

sakra