Tim
Tim

Reputation: 99428

Deal with space in pathname in cmd

C:\Program Files\mu-repo>mu
python: can't open file 'C:\Program': [Errno 2] No such file or directory


C:\Program Files\mu-repo>cat mu.bat
@echo off
python %~dp0\mu %*

When I change the mu.bat to have the absolute pathname of mu.bat, the batch file can be found:

C:\Program Files\mu-repo>cat mu.bat
@echo off
python "C:\Program Files\mu-repo"\mu %*

C:\Program Files\mu-repo>mu
Commands:

* mu register repo1 repo2: Registers repo1 and repo2 to be tracked.
* mu register --all: Registers all subdirs with .git (non-recursive).

How can I keep using %~dp0, without replacing it with the absolute pathname?

Thanks.

Upvotes: 0

Views: 498

Answers (1)

mklement0
mklement0

Reputation: 438093

Change mu.bat to the following:

@echo off
python "%~dpn0" %*
  • The enclosing "..." ensures that the path is recognized as a single argument, even if it contains spaces.

  • Note that I've added n to %~dp0, which adds the batch file's filename root (the filename without extension) - mu, in this case - to the resulting path, resulting in C:\Program Files\mu-repo\mu overall.

A few asides:

  • The syntax of expressions such as %~dp0 - a modified reference to %0, which contains the path to the batch file as invoked - is explained when you run help call.
    As aschipfl points out in a comment on the question, the d part expands to the directory path including a trailing \, so there is no need to append one.

  • Do not double-quote %* ("%*") to pass all arguments through, as that results in a different command line - just use %* as-is (unquoted).

  • It is permissible to mix double-quoted and unquoted parts in a single argument; given that mu by itself doesn't need double-quoting, both "%~dp0"mu and "%~dp0mu" would work.

Upvotes: 1

Related Questions