What happens during set "x=%y%" ?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
WernerGg
Posts: 19
Joined: 06 May 2011 08:07
Location: Stuttgart, Germany, currently Riyadh, KSA

What happens during set "x=%y%" ?

#1 Post by WernerGg » 07 May 2011 11:28

I had a

Code: Select all

set x=%y%

somewhere in my code and the program did not work. I needed hours to find that my editor (TextPad) had left a space at the end of that line which was then appended to x.

Sometimes I saw code like

Code: Select all

set "x=%y%"

which I did not understand and which should be an error according to the specification of the SET statement, which is

Code: Select all

set [variable=[string]]


Q1: Is the reason for that kind of coding with string delimitters just to avoid the problem with trailing spaces?

Q2: What happens really during execution of that statement? Does the command interpreter just throw the apostrophes away? But take the second apostrophe as end-of-line?

Actually I can write

Code: Select all

set "x=any value" and then comments


Q3: Why is that legal?

Q4: Would it not be reasonable, if not compelling, to use that kind of coding always?

aGerman
Expert
Posts: 4654
Joined: 22 Jan 2010 18:01
Location: Germany

Re: What happens during set "x=%y%" ?

#2 Post by aGerman » 07 May 2011 14:41

I think jeb should answer your questions because he spends a lof of time to figure out how the command interpreter works.
Finally (as you probably found out by yourself) it is legal. It's useful to avoid trailing spaces as well as to protect you from problems caused by special characters like ^<>|&. If you want to use it it's important to know that you have to write the first double quote in front of the variable. In this case the variable value is everyting after the equal sign until the last double quote in this line.

Regards
aGerman

jeb
Expert
Posts: 1042
Joined: 30 Aug 2007 08:05
Location: Germany, Bochum

Re: What happens during set "x=%y%" ?

#3 Post by jeb » 08 May 2011 11:18

@aGerman: You have answered the question already.

The only thing left are two little tricks.

An exlamation trick while using delayed expansion
set "myVar=hel^lo" !
The appended exlamation mark forces the delayed phase to remove one more time the carets.
This can be usefull in automatic return statements
new functions: :chr, :asc, :asciiMap
Describes also return a value the perfect way.

The qutoed/unquote trick

Code: Select all

set ^"myVar=hello^

LF inserted"


So you can use quotes but also the caret escape for appending linefeeds

jeb

Post Reply