Roast Chicken
Roast Chicken

Reputation: 13

Escaping outputs in CMD

If I run something that returns with a & or some other character that has special meaning, and I try to use it in a script, how would I escape it?

An example would be if I shared a local account with someone in the same computer, and I had a username that says John & Matt. Putting a batch file in the Desktop directory that had something like this:

@ECHO OFF
echo %~dp0

It would return something like this:

C:\Users\John
The system cannot find the path specified.

And the whole script from that point on breaks if I try to keep going. If anyone knows a way to make the whole path appear, I'd appreciate it.

EDIT: I didn't clarify this enough earlier. Sorry about that. Not really good at explaining, but if I try to use %~dp0 in a variable, and stack more things on top of that, something like

SETLOCAL
set loc=%~dp0
rename "%~dp0Dir\Dir1\Dir2\File.txt" "Something.txt"

It would probably confuse the rename command if I put another set of quotation marks when I'm declaring a variable to fix that issue.

The batch file that I was trying to create basically deletes a file where the batch file is located, replaces it with another file in a subfolder located inside the directory where the batch file is, and renames it to something else.

Upvotes: 1

Views: 277

Answers (2)

dbenham
dbenham

Reputation: 130819

If you want to reliably ECHO the value without enclosing quotes, then you can use either of the following strategies:

@echo off
:: Use a FOR loop
for %%F in ("%~dp0") do echo %%~F

:: Use delayed expansion.
:: Note that delayed expansion must be enabled after assignment of fullPath,
:: else any ! within path will be corrupted during the assignment.
set "fullPath=%~dp0"
setlocal enableDelayedExpansion
echo !fullPath!

Upvotes: 3

MichaelS
MichaelS

Reputation: 6032

@ECHO OFF
echo %dp0

will return dp0 - I guess you mean %~dp0 ;-)

However, echo "%~dp0" will output C:\Users\John & Matt\...

By the way, it's \ and not /.

Windows: \

Unix/Linux: /

I'm not being pedantic, this sometimes causes serious problems (like here).

Upvotes: 0

Related Questions