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?
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:
This works independently of the length of your directory names.
The
pushdcommands change directories (and remember where it came from) — thepopdcommands go back to what was remembered bypushd. The%cd%variable holds the current drive+path.