Search code examples
cmdbatch-filepathname

bat file: get parent pathname


The following mostly works. 'Mostly', because the use of the SOMETHING..\tasks\ pathname confuses Spring when a context XML file tries to include another by relative pathname. So, what I seem to need is a way, in a BAT file, of setting a variable to the parent directory of a pathname.

set ROOT=%~dp0
java -Xmx1g -jar %ROOT%\..\lib\ajar.jar %ROOT%\..\tasks\fas-model.xml tasks

Solution

  • To resolve a relative path name you can utilize a sub routine call. At the end of your batch file place the following lines:

    GOTO :EOF
    
    :RESOLVE
    SET %2=%~f1 
    GOTO :EOF
    

    This is a sub routine that resolves its first parameter to a full path (%~f1) and stores the result to the (global) variable named by the 2nd parameter

    You can use the routine like this:

    CALL :RESOLVE "%ROOT%\.." PARENT_ROOT
    

    After the call you can use the variable %PARENT_ROOT% that contains the parent path name contained in the %ROOT% variable.

    Your complete batch file should look like this:

    SET ROOT=%~dp0
    
    CALL :RESOLVE "%ROOT%\.." PARENT_ROOT
    
    java -Xmx1g -jar "%PARENT_ROOT%\lib\ajar.jar" "%PARENT_ROOT%\tasks\fas-model.xml" tasks
    
    GOTO :EOF
    
    :RESOLVE
    SET %2=%~f1 
    GOTO :EOF