How do I find the current directory of a batch file, and then use it for the path?

后端 未结 4 1782
悲哀的现实
悲哀的现实 2020-11-29 04:12

I have a batch file that I intend to distribute to our customers to run a software task.

We distribute them as a folder or .zip with the files inside.

4条回答
  •  囚心锁ツ
    2020-11-29 04:47

    There is no need to know where the files are, because when you launch a bat file the working directory is the directory where it was launched (the "master folder"), so if you have this structure:

    .\mydocuments\folder\mybat.bat
    .\mydocuments\folder\subfolder\file.txt
    

    And the user starts the "mybat.bat", the working directory is ".\mydocuments\folder", so you only need to write the subfolder name in your script:

    @Echo OFF
    REM Do anything with ".\Subfolder\File1.txt"
    PUSHD ".\Subfolder"
    Type "File1.txt"
    Pause&Exit
    

    Anyway, the working directory is stored in the "%CD%" variable, and the directory where the bat was launched is stored on the argument 0. Then if you want to know the working directory on any computer you can do:

    @Echo OFF
    Echo Launch dir: "%~dp0"
    Echo Current dir: "%CD%"
    Pause&Exit
    

提交回复
热议问题