批处理文件变量操作

时间:2013-11-21 21:17:21

标签: batch-file

有谁知道为什么这不起作用?我希望它要求一个字符串,例如1,2或exampletext。然后检查输入值是否为1,然后将变量更改为ABC,如果为2,则更改为DEF,否则保持不变。

@echo off
set /p id="Enter ID: " %=%
IF "%id%" == "1"(
   set id="ABC"
)
ELSE (
   IF "%id%" == "2"(
      set id="DEF"
   )
   ELSE (
      PING 127.0.0.1 -n 0.1 >nul  
   )
)
Start "" "C:\Users\Comp\Desktop\livestreamer-1.5.2-win32\livestreamer.exe" twitch.tv/%id% mobile_High

2 个答案:

答案 0 :(得分:5)

虽然乔伊已经指出错误的原因,但我无法抗拒向你展示不同方法的诱惑:

@echo off
setlocal EnableDelayedExpansion

rem Define the table of equivalences:
set equiv[1]=ABC
set equiv[2]=DEF

set /p "id=Enter ID: " %=%
if defined equiv[%id%] (
   set id=!equiv[%id%]!
) ELSE (
   PING 127.0.0.1 -n 0.1 >nul  
)
Start "" "C:\Users\Comp\Desktop\livestreamer-1.5.2-win32\livestreamer.exe" twitch.tv/%id% mobile_High

此方法使用数组。如果您对此方法感兴趣,请搜索“延迟扩展”和“批量数组”。

答案 1 :(得分:3)

你只是缺少一些空格(在if的左括号之前)。并且else需要与右括号¹:

在同一行
IF "%id%" == "1" (
   set id=ABC
) ELSE (
   IF "%id%" == "2" (
      set id=DEF
   ) ELSE (
      PING 127.0.0.1 -n 0.1 >nul  
   )
)

另请注意,=中的set之后的引号会逐字包含在变量中,这不是您想要的。

您还可以简化一下:

if "%id%=="1" (
  set id=ABC
) else if "%id%=="2" (
  set id=DEF
) else (
  ping localhost -n 1 >nul
)

¹在第一页的help if中甚至拼写出来:“ELSE子句必须与IF之后的命令在同一行上。”

相关问题