【问题标题】:Prevent batch script from terminating upon invalid character input防止批处理脚本因输入无效字符而终止
【发布时间】:2017-02-01 08:36:33
【问题描述】:

我在编写批处理脚本时总是遇到这个问题。每当我让脚本提示用户设置变量时,如果输入了分号(这只是一个示例),则脚本将关闭。有没有办法阻止它这样做?

例子:

@echo off
:1
cls
echo Please enter your ID:
set /P id=
if /i %id%==119 goto Tom
if /i %id%==204 goto Brittany
if /i %id%==12 goto Shannon
if /i %id%==64 goto Jack
goto 1

:Tom
cls
echo Tom, you have to mow the lawn.
pause>nul
exit

:Brittany
cls
echo Brittany, you have to fold the laundry.
pause>nul
exit

:Shannon
cls
echo Shannon, you have to feed the dog.
pause>nul
exit

:Jack
cls
echo Jack, you have to replace the radio's capacitors.
pause>nul
exit

我会看到运行该脚本的内容:

C:\>myscript.bat
Please enter your ID:
asjfash;dfjlas;ldf
asjfash;dfjlas;ldf==i was unexpected at this time.

脚本关闭。

谢谢!

【问题讨论】:

  • edit您的问题并分享您的失败代码,按照如何创建minimal reproducible example
  • 抱歉,JosefZ,我还是新手。
  • 显示 result 是正确且必要的,但还不够;也显示你失败的代码。阅读Syntax : Escape Characters, Delimiters and Quotes。当然,您需要转义分号,例如就像在这个例子中:if /i "%varname%"=="literal;string" call :labelE
  • 最诚挚的歉意,我已经添加了一些示例代码。

标签: windows batch-file variables scripting


【解决方案1】:

读取语法:Escape Characters, Delimiters and Quotes:

分隔符

分隔符将一个参数与下一个参数分开 - 它们将 将命令行组合成单词。

参数通常由空格分隔,但任何 以下也是有效的分隔符:

  • 逗号 (,)
  • 分号 (;)
  • 等于 (=)
  • 空格 ()
  • 制表符 (   )

如果用户输入了一些包含上述任何分隔符的字符串(如set "id=1 19" 那么%id% 包含一个空格),那么

if /i %id%==119 goto Tom

结果 if /i 1 19==119 goto Tom ↑ this space causes error 19==119 was unexpected at this time

当然,您需要转义分隔符和所有其他cmd-poisonous 字符,如下所示:

@echo off
:1
cls
echo Please enter your ID:
set /P id=
if /i "%id%"=="119" goto Tom
if /i "%id%"=="204" goto Brittany
if /i "%id%"=="12"  goto Shannon
if /i "%id%"=="64"  goto Jack
goto 1

rem script continues here

仅供参考,Redirection article 列出了其他需要转义的 cmd-有毒字符,因为它们在批处理脚本中未转义的出现具有以下含义:

  • &  - 单与号:用作命令分隔符
  • && - 双与号:条件命令分隔符(如if errorlevel 0
  • || - 双管(垂直线):条件命令分隔符(如if errorlevel 1
  • - 单管道:将一个命令的 std.output 重定向到另一个命令的 std.input
  • >  - 单个大于:将输出重定向到文件或类似设备的文件
  • >> - 双大于:输出将被添加到文件的最后
  • <  - 小于:将文件内容重定向到命令的 std.input

【讨论】:

  • 非常感谢您帮我解决这个问题!那么,当我使用引号时,这是否意味着它只会转到我输入的内容?
  • 是的,确实如此。但是,尝试for %G in ("1<2,64;119") do @for %g in (%~G) do @echo "%g" from 并打开cmd 窗口以查看如何解析多个用户的输入。在批处理脚本中,将循环变量 %G%g 加倍 % 签名为 for %%G in ("1<2,64;119") do for %%g in (%%~G) do echo "%%g"
  • 对不起,我不太明白
猜你喜欢
  • 1970-01-01
  • 2012-11-17
  • 2015-05-08
  • 2011-09-24
  • 1970-01-01
  • 2017-04-22
  • 2018-10-20
  • 1970-01-01
  • 2020-11-02
相关资源
最近更新 更多