How to get the path of the batch script in Windows?

前端 未结 8 1313

I know that %0 contains the full path of the batch script, e.g. c:\\path\\to\\my\\file\\abc.bat

I would path to be equal to

相关标签:
8条回答
  • 2020-12-04 05:15

    %~dp0 - return the path from where script executed

    But, important to know also below one:

    %CD% - return the current path in runtime, for example if you get into other folders using "cd folder1", and then "cd folder2", it will return the full path until folder2 and not the original path where script located

    0 讨论(0)
  • 2020-12-04 05:17

    %~dp0 will be the directory. Here's some documentation on all of the path modifiers. Fun stuff :-)

    To remove the final backslash, you can use the :n,m substring syntax, like so:

    SET mypath=%~dp0
    echo %mypath:~0,-1%
    

    I don't believe there's a way to combine the %0 syntax with the :~n,m syntax, unfortunately.

    0 讨论(0)
  • 2020-12-04 05:17

    %cd% will give you the path of the directory from where the script is running.

    Just run:

    echo %cd%
    
    0 讨论(0)
  • 2020-12-04 05:21

    You can use following script to get the path without trailing "\"

    for %%i in ("%~dp0.") do SET "mypath=%%~fi"
    
    0 讨论(0)
  • 2020-12-04 05:23

    %~dp0 may be a relative path. To convert it to a full path, try something like this:

    pushd %~dp0
    set script_dir=%CD%
    popd
    
    0 讨论(0)
  • 2020-12-04 05:26

    I am working on a Windows 7 machine and I have ended up using the lines below to get the absolute folder path for my bash script.

    I got to this solution after looking at http://www.linuxjournal.com/content/bash-parameter-expansion.

    #Get the full aboslute filename.
    filename=$0
    #Remove everything after \. An extra \ seems to be necessary to escape something...
    folder="${filename%\\*}"
    #Echo...
    echo $filename
    echo $folder
    
    0 讨论(0)
提交回复
热议问题