M HYPE SPLASH
// general

What is a windows bat analog of cd $(dirname $0)?

By Andrew Adams

I've looking pretty long to get answer on this simple question and finally got it. Want to share with those who will port shell scripts to the bat analogs.

1

3 Answers

Simple solution is:

cd /d "%~dp0"

%0 contains the full path of the running .bat or .cmd file.

The ~ expansions can be applied to all numbered arguments (%0%9) and to the one-letter variables used by FOR (e.g. %%a). The most commonly used expansions are:

  • ~d: drive letter (with colon)
  • ~p: directory path (without drive letter)
  • ~n: file name without extension
  • ~x: file extension (with leading dot)

So combining them into %~dp0 will work like dirname, while %~nx0 will work like basename.

2

The answer described by @Stand Alone is not completely reliable, because if the script in is another drive rather than current directory, It will not work. So some other solutions are:

Method 1

pushd "%~dp0"

Method 2

cd /d "%~dp0"

Note: To change directory to the last set directory, popd command can be used. This only works after changing the directory using #method 1.

cd /d "%0\.."

Every filename can be used as a dir path ))

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy