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?
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:
yields
You can protect the carets by quoting the string, but then you get the quotes in your ECHO result:
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:
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:
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: