Resolve absolute path from relative path and/or file name

前端 未结 14 1587
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 09:38

Is there a way in a Windows batch script to return an absolute path from a value containing a filename and/or relative path?

Given:

         


        
相关标签:
14条回答
  • 2020-11-27 10:05
    SET CD=%~DP0
    
    SET REL_PATH=%CD%..\..\build\
    
    call :ABSOLUTE_PATH    ABS_PATH   %REL_PATH%
    
    ECHO %REL_PATH%
    
    ECHO %ABS_PATH%
    
    pause
    
    exit /b
    
    :ABSOLUTE_PATH
    
    SET %1=%~f2
    
    exit /b
    
    0 讨论(0)
  • 2020-11-27 10:09

    Small improvement to BrainSlugs83's excellent solution. Generalized to allow naming the output environment variable in the call.

    @echo off
    setlocal EnableDelayedExpansion
    
    rem Example input value.
    set RelativePath=doc\build
    
    rem Resolve path.
    call :ResolvePath AbsolutePath %RelativePath%
    
    rem Output result.
    echo %AbsolutePath%
    
    rem End.
    exit /b
    
    rem === Functions ===
    
    rem Resolve path to absolute.
    rem Param 1: Name of output variable.
    rem Param 2: Path to resolve.
    rem Return: Resolved absolute path.
    :ResolvePath
        set %1=%~dpfn2
        exit /b
    

    If run from C:\project output is:

    C:\project\doc\build
    
    0 讨论(0)
  • 2020-11-27 10:10

    You can also use batch functions for this:

    @echo off
    setlocal 
    
    goto MAIN
    ::-----------------------------------------------
    :: "%~f2" get abs path of %~2. 
    ::"%~fs2" get abs path with short names of %~2.
    :setAbsPath
      setlocal
      set __absPath=%~f2
      endlocal && set %1=%__absPath%
      goto :eof
    ::-----------------------------------------------
    
    :MAIN
    call :setAbsPath ABS_PATH ..\
    echo %ABS_PATH%
    
    endlocal
    
    0 讨论(0)
  • 2020-11-27 10:13

    Most of these answers seem crazy over complicated and super buggy, here's mine -- it works on any environment variable, no %CD% or PUSHD/POPD, or for /f nonsense -- just plain old batch functions. -- The directory & file don't even have to exist.

    CALL :NORMALIZEPATH "..\..\..\foo\bar.txt"
    SET BLAH=%RETVAL%
    
    ECHO "%BLAH%"
    
    :: ========== FUNCTIONS ==========
    EXIT /B
    
    :NORMALIZEPATH
      SET RETVAL=%~f1
      EXIT /B
    
    0 讨论(0)
  • 2020-11-27 10:15

    You can just concatenate them.

    SET ABS_PATH=%~dp0 
    SET REL_PATH=..\SomeFile.txt
    SET COMBINED_PATH=%ABS_PATH%%REL_PATH%
    

    it looks odd with \..\ in the middle of your path but it works. No need to do anything crazy :)

    0 讨论(0)
  • 2020-11-27 10:17

    In your example, from Bar\test.bat, DIR /B /S ..\somefile.txt would return the full path.

    0 讨论(0)
提交回复
热议问题