Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to echo a environment variable contains a '&' in DOS batch?

When I type:

set hi=Hello^&World!
echo %hi%

it print Hello and tell me World is not a command

I want it prints Hello&World!

How to do this?

like image 493
Celebi Avatar asked Sep 21 '11 07:09

Celebi


2 Answers

This works for me:

set "hi=Hello^&World!"
echo %hi%

Outputs

Hello&World!
like image 82
Bali C Avatar answered Oct 04 '22 10:10

Bali C


The only secure way to echo the content of a variable is to use the delayed expansion here.
If percent expansion is used, it depends on the content if it fails.

set "var1=Hello ^& World"
set "var2=Hello & World"
setlocal EnableDelayedExpansion
echo !var1!
echo !var2!
echo %var1%
echo %var2% -- fails

The delayed expansion is more usefull as it doesn't interpret any special characters.
More info at SO: How the parser works

like image 25
jeb Avatar answered Oct 04 '22 11:10

jeb