0

I just started programming in batch. I tried to execute the following code in a .bat file, and also in CMD directly. In either case I receive a blank space.

ECHO My name is agent Smith |  SET /P Name="What is your name?"
ECHO Result is %Name%

A found this code in a book about batch programming, but does not work.

Somewhere i read that echo is in a different context, and SET /P only accepst user entered things.

  • 3
    A pipe initiates a new `cmd.exe` instance for either side, so the variable in the hosting instance is not altered: `echo Test| (set /P VAR=& set VAR)` will return `VAR=Test`, but `echo Test| set /P VAR=& set VAR` will not (given that `VAR` is not initially set)… – aschipfl Jul 07 '21 at 19:20
  • *N. B.:* Would you mind telling us what book you are talking about? – aschipfl Jul 07 '21 at 19:26
  • I tried like you wrote: `ECHO My name is agent Smith | (SET /P Name= & SET Name )` directly in cmd it gets me: `Name=My name is agent Smith` but in a file it does not, I run the file from cmd like c:\User>pipe-1.bat – RobertZ Jul 07 '21 at 19:29
  • The book is: Batchography: The Art of Batch files programming – RobertZ Jul 07 '21 at 19:37
  • There should be no difference whether the code is directly run in Command Prompt or within a batch file, pipes behave just the same… – aschipfl Jul 08 '21 at 08:40

1 Answers1

1

I'd take a look at this stack overflow for a more in depth discussion on what's causing the problem. In short pipe operator evaluates the left and right side in separate threads. This means that SET /P Name= sets the environment variable Name in its thread's context and not the invoking thread's context. This can more clearly be seen in following example:

set name=invokingContext
echo threadContext | (set /p name= & set name)
set name

which outputs:

name=threadContext
name=invokingContext

Assuming you have write permissions, an easy way to get around this limitation is to use temporary files and redirection:

echo My name is agent Smith > tmp.txt
set /p Name=What is your name < tmp.txt
echo %Name%

Which outputs:

What is your name
My name is agent Smith
  • Thank you very much, this work just fine! with an additional `DEL tmp.txt` line I do not mak unnacasarry files. However I still wonder why the first code I tried didn-t work? I mean it is from a book which I assume is not bad. Is it becaouse it was written in 2016? – RobertZ Jul 07 '21 at 20:06