Unable to echo user input values to file in Batch

2019-09-15 03:39发布

问题:

I am writing a batch file that will generate/write to a property file based on multiple user input values. However, it is not recording the values of input. The result looks like

prop1=
prop2=

I wonder if there's something I need to know with set that is preventing this from working.

Weird part is that if I run this particular script multiple times, the value output from echo seems to be always be the user input from last time.

Code:

@echo off

IF NOT EXIST data_file (
set /p prop1=Enter value: 
set /p prop2=Enter value: 
(echo prop1=%prop1%) > data_file 
(echo prop2=%prop2%) >> data_file 
) 

回答1:

Classic problem for inexperienced batchers :)

%prop1% is expanded when the line is parsed. Your problem is that everthing within parentheses is parsed in one pass. So the value you see is the value that existed before you entered the IF statement.

You have two simple solutions.

1) Eliminate the enclosing parens by reversing the logic and using GOTO

@echo off
IF EXIST file goto skip
set /p prop1=Enter value: 
set /p prop2=Enter value: 
(echo prop1=%prop1%) >file 
(echo prop2=%prop2%) >>file 
:skip

2) Use delayed expansion - that takes place just before each line within the parens is executed

@echo off
setlocal enableDelayedExpansion
IF NOT EXIST file (
  set /p prop1=Enter value: 
  set /p prop2=Enter value: 
  (echo prop1=!prop1!)>file
  (echo prop2=!prop2!)>>file
)


回答2:

You need to expand the variables using SETLOCAL ENABLEDELAYEDEXPANSION or use CALL.

@echo off

IF NOT EXIST data_file (
    set /p prop1=Enter value: 
    set /p prop2=Enter value:

    (
    Call echo prop1=%%prop1%%
    Call echo prop2=%%prop2%%
    ) > data_file 

)