How to SET a variable to the path of parent directory on windows?

前端 未结 3 1156
日久生厌
日久生厌 2020-12-30 02:59

Struggling with command line again, I have figure out that I can store the current working directory in a variable like so:

SET current=%cd%
<
相关标签:
3条回答
  • 2020-12-30 03:18

    You could also do something like this:

    set current=%CD%
    set parent=%CD%\..
    

    It doesn't give you the canonical name of the parent, but it should always be a valid path to the parent folder. It will also be somewhat faster than the solutions involving pushd and popd, but that won't be the primary consideration in a batch file.

    Edit: Note that all of the solutions so far, including mine here, will have problems if the current folder is the root of a drive. There is no clean and easy way out of that one, since there really is no parent of a drive visible to user mode.

    0 讨论(0)
  • 2020-12-30 03:34

    Move up a directory, remembering the current, set the parent, and then pop down a directory, back to where you started

    @echo off
    set current=%cd%
    pushd ..
    set parent=%cd%
    popd
    
    echo current %current%
    echo parent %parent%
    
    0 讨论(0)
  • 2020-12-30 03:36

    Use

    pushd targetFolder
    set current=%cd%
    popd
    

    Pushd/popd maintain a stack of previously visited directories.

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