Celebi
Celebi

Reputation: 1310

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?

Upvotes: 6

Views: 58292

Answers (3)

jeb
jeb

Reputation: 82202

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

Upvotes: 5

PA.
PA.

Reputation: 29339

just

echo Hello ^& World!

works

EDIT so the problem is not with ECHO command, but with the assignment of the variable, as @Bali correctly pointed out.

Upvotes: 3

Bali C
Bali C

Reputation: 31231

This works for me:

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

Outputs

Hello&World!

Upvotes: 22

Related Questions