tags:

views:

31

answers:

1
C:\>type c:\output.txt
abcd
C:\>type c:\output.txt | set /p V1=

C:\>set
... A bunch of junk, NOT seeing "V1"

What happened? According to all documentation for SET I've seen, %V1% should have been assigned a value of "abcd" from the above, no?

I'm on Windows XP Pro, SP3 if it matters.

+3  A: 

I don't know what doco you've seen for the set command but the output of set /? clearly states:

The /P switch allows you to set the value of a variable to a line of input entered by the user.

(my italics). I think set /p is getting its input from the console regardless of what you're trying to pipe in through standard input. Why it's not waiting, I'm not sure. echo xxx | set /p xx= also fails to set the variable.

But, if you want to set a variable from a single line file, you can just use one of these:

for /f "delims=" %%i in (c:\output.txt) do set V1=%%i
set /p V1=<c:\output.txt

That second one is the simplest but it doesn't help much if you want to grab the output of an arbitrary command but you may well have to direct it to a file first.

The first one allows you to execute arbitrary commands without temporary files:

for /f "delims=" %%i in ('echo AAA') do set xx=%%i

There's an interesting snippet on this page which suggests it has to do with contexts:

Ok, I found out why myself. It's because the | creates a new context so the variable never makes it out to the rest of the current context. Proof:
> set bar=
> echo aaa | (set /p bar= && set bar)
bar=aaa
> set bar
Environment variable bar not defined

although I decline to comment on the veracity of that conclusion. I don't know what contexts are in this sense, I'm just bringing it to your attention for completeness.

paxdiablo
@pax - Sorry, I haven't done any batch coding in over 10 years and thus my head is polluted by Unix notions that STDIN is STDIN ... I guess you are right that "by the user" is not synonymous with "STDIN" in DOS-world by default (yes, I know about wanky TTY detection stuff some Unix programs pull, but that's a rare and hard to achieve exception :) I will need to read more about these contexts (actually saw that page last night but was too tired to parse it fully.
DVK
Well, I think you're actually right, @DVK, despite my original paragraphs in the above answer. It's clearly _some_ sort of STDIN since `set /p V1=<c:\output.txt` works fine. It's just the pipe variety that doesn't seem to work.
paxdiablo