2

In Windows 7's cmd, I understand that %~dp0 gives the folder path of a batch file, as in How to get folder path from file path with CMD

However, it doesn't work if there is at least one caret (^) in the path. For example, a batch in C:\one^two^^three^^^four^^^^carets\ containing

echo %~dp0

gives

C:\onetwo^three^four^^carets\

How can I escape the carets?

Community
  • 1
  • 1
Gnubie
  • 2,587
  • 4
  • 25
  • 38

2 Answers2

6

You are getting the correct value, but it has to go through another layer of parsing when you ECHO the value. An unquoted ^ is the batch escape character used to turn special characters like & and | that have meaning into simple literal characters. Whatever character follows an unquoted caret is escaped and the caret is consumed.

You would get the exact same result if you were to simply ECHO the string literal:

echo C:\one^two^^three^^^four^^^^carets\

yields

C:\onetwo^three^four^^carets\

You can protect the carets by quoting the string, but then you get the quotes in your ECHO result:

echo "%~dp0"

You can easily transfer the original value to an environment variable without consuming carets and prove it by using SET to look at the result:

@echo off
setlocal
set "myPath=%~dp0"
set myPath

If you want to ECHO just the value without quotes, you could use delayed expansion. This works because delayed expansion occurs after parsing of special characters:

@echo off
setlocal enableDelayedExpansion
set "myPath=%~dp0"
echo !myPath!

You could also get the same result by transferring the value to a FOR variable. Expansion of FOR variables also occurs after special character parsing:

@echo off
for %%A in ("%~dp0") do echo %%~A
dbenham
  • 127,446
  • 28
  • 251
  • 390
  • +1 for the detailed explanation and examples. The "echo !myPath!" solution is correct. Both the others enclose the string in quotes. – Gnubie Oct 11 '12 at 11:16
  • @Gnubie - Oops, thanks! I was missing the `~` in my last example that strips the quotes. All fixed now. – dbenham Oct 11 '12 at 11:20
0

Have you tried delayed variable expansion?

echo !dp0

I don't know if it compatible with quote-stripping ~

John Watts
  • 8,717
  • 1
  • 31
  • 35