无法回应用户输入值在批处理脚本到文件 [英] Unable to echo user input values to file in Batch script

查看:174
本文介绍了无法回应用户输入值在批处理脚本到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个批处理文件,将生成/写入基于多个用户输入值的属性文件。然而,这不是记录输入的值。结果看起来像

 为prop1 =
prop2 =

我不知道是否有什么东西我需要知道与集是preventing这无法工作。

怪异的一部分是,如果我运行这个特定脚本多次,从回音的输出值似乎永远是从最后一次的用户输入。

code:

 关闭@echoIF NOT EXIST DATA_FILE(
集/ p为prop1 =输入值:
集/ p prop2 =输入值:
(回声为prop1 =%为prop1%)GT; DATA_FILE
(回声prop2 =%prop2%)GT;> DATA_FILE


解决方案

经典问题,对于没有经验的计量:)

%为​​prop1%当行被解析扩展。你的问题是,括号中全部的寄托在一个通被解析。所以你看到的值是您输入的IF语句之前存在的价值。

您有两个简单的解决方案。

1)通过反向逻辑,并使用GOTO消除封闭括号

 关闭@echo
如果存在的文件转到跳过
集/ p为prop1 =输入值:
集/ p prop2 =输入值:
(回声为prop1 =%为prop1%)GT;文件
(回声prop2 =%prop2%)GT;>文件
:跳跃

2)使用延迟扩展 - 这发生的只是每一个前行的括号内执行

 关闭@echo
SETLOCAL enableDelayedExpansion
如果不存在的文件(
  集/ p为prop1 =输入值:
  集/ p prop2 =输入值:
  (!回声为prop1 =为prop1!)>文件
  (!回声prop2 = prop2!)>>文件

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 
) 

解决方案

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
)

这篇关于无法回应用户输入值在批处理脚本到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆