When to use "SET var=input"?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
tinfanide
Posts: 117
Joined: 05 Sep 2011 09:15

When to use "SET var=input"?

#1 Post by tinfanide » 06 Apr 2012 03:48

Based on the previous post
http://www.dostips.com/forum/viewtopic.php?f=3&t=3160,

I wonder what happens to the CMD console.

Code: Select all


FOR /F "tokens=1" %%A IN (log.log) DO SET var=%%A & CALL :next
GOTO :end

:next
ECHO %var% > %var%.txt
GOTO :EOF

:end
PAUSE>NUL



It turns out to be four files:
a
b
c
d


If I use this or that:

Code: Select all

SET "var=%%A"

or

Code: Select all

ECHO %var% > "%var%.txt"


The extension ".txt" is processed.

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: When to use "SET var=input"?

#2 Post by dbenham » 06 Apr 2012 06:20

The following code

Code: Select all

... DO SET var=%%A & CALL :next
introduces a space at the end of the value for var.

Assuming %%A="a", then using

Code: Select all

echo %var% > "%var%.txt"
should create a file named "a .txt" containing the value "a ". Note there are 2 spaces at the end of the content - one from the var assignment, and one because you have a space before your redirection.

If you drop the quotes from the redirection

Code: Select all

echo %var% > %var%.txt
then it should create a file named "a" containing the value "a .txt". Redirection can occur anywhere within a line. The parser assumes the file name stops at the space because it is not quoted. The rest of the line is treated as part of the content of the echo command.

You can eliminate the unwanted spaces by simply removing them from your code

Code: Select all

... DO SET var=%%A&CALL :next
...
echo %var%>"%var%.txt"
This should create a file named "a.txt" containing the value "a".

Another option is to use quotes in the assignment, and move the redirection to the front. Then extra spaces are ignored.

Code: Select all

... DO SET "var=%%A" & CALL :next
...
>"%var%.txt" echo %var%
Note that I still enclosed the file name in quotes. I recommend always doing so in case the value of var contains a space or special characters.

Dave Benham

tinfanide
Posts: 117
Joined: 05 Sep 2011 09:15

Re: When to use "SET var=input"?

#3 Post by tinfanide » 06 Apr 2012 06:41

Yes, you so detailed demo was actually what I'd just done in my CMD console and I jumped to the same conclusion.
In other programming languages like JavaScript or C#, I am used to using (indeed it seems a must to use "") quotes to "protect" or avoid the spaces.
And when it came to DOS commands, I was stocked by so many online examples where SET var=something that no spaces near = and DOS coders seem not to use quotes.
But anyway, thanks for the explanation.

Post Reply