Silver
Silver

Reputation: 67

How to escape %%

I am trying to write a very simple batch script which echos onto another batch file in order to keep things organised. Whilst doing this, I noticed that if I did something like:

@echo if %cd%==C:\Users\whoever\Desktop msg * success

then it would echo the current directory, since I put in "%cd%". How would I escape this so that it instead echos %cd%, rather then: C:\Users\whoever\desktop\file

Thanks for all the help!

Upvotes: 1

Views: 104

Answers (2)

Stephan
Stephan

Reputation: 56238

escaping can be a bit un-intuitive.

within batchfiles, % are escaped with another %: echo %%cd%%

on command line you can't really escape them but "fake-escaping" them with a caret: echo ^%cd^% does the trick, because cmd shows %varName%, if varname isn't defined, so trying to show the non-defined variable cd^ shows %cd% instead (the parser swallows the caret). The starting caret is not really needed, but makes the "fake-escaping" more consistent.

C:>@echo if ^%cd^%==C:\Users\whoever\Desktop msg * success
if %cd%==C:\Users\whoever\Desktop msg * success
C:>type t.bat
@echo if %%cd%%==C:\Users\whoever\Desktop msg * success   
C:>t
if %cd%==C:\Users\whoever\Desktop msg * success
C:>

Upvotes: 3

dxiv
dxiv

Reputation: 17678

I don't know of an elegant one-liner, but the following will work:

@echo off
set "random=cd"
echo %%%random%%% = "%cd%"
set "random="

Output:

%cd% = "C:\Users\whoever\desktop\file"

Note that the temporary variable does not need to be named random, only since it's a reserved name chances are lower that it would overwrite some other defined variable.


[ EDIT ] An alternative, in case the construct is used repeatedly, would be the following (at the expense of using a dedicated environment variable pct):

@echo off
set "pct=%%"
echo %pct%cd%pct% = "%cd%"

Upvotes: 2

Related Questions