Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

windows - Difference between %variable% and !variable! in batch file

I am writing a batch file where I need to output a string containing '!' to another file. But when I echo that string to another file, it removes "!" from the output.

Eg: Input:

set LINE=Hi this is! output
echo !LINE!>>new_file.txt

Output in new_file.txt is:

Hi this is output

Also, if input is

set LINE=Hello!! this is output!!
echo !LINE!>>new_file.txt

Output in new_file.txt:

Hello

Hence, it skips the ! (Exclamation mark) from the output to the new_file. If I use %LINE%, then it simply displays "echo is on" to the output file.

Please suggest a way to overcome this problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you have delayed expansion enabled and want to output an exclamation mark, you need to escape it.

Escaping of exclamation marks needs none, one or two carets, depending on the placement.

@echo off
REM No escaping required, if delayed expansion is disabled
set test1=Test1!

setlocal EnableDelayedExpansion
REM One caret required
REM Delayed expansion uses carets independent of quotes to escape the exclamation mark
set "test2=Test2^!"

REM Two carets required
REM The first caret escapes the second caret in phase2 of the parser
REM Later in the delayed expansion phase, the remaining caret escapes the exclamation mark
set test3=Test3^^!


echo !test1!
echo !test2!
echo !test3!

The difference between !var! and %var% in blocks is explained at DOS batch: Why are my set commands resulting in nothing getting stored?

An explanation of the batch parser can be found at How does the Windows Command Interpreter (CMD.EXE) parse scripts?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...