我想批量制作一个基本的文本编辑器,我正在使用set/p来获取用户输入并将其写入文件。
当我输入诸如"hello"或"hello "之类的内容时,它可以正常工作,但是一旦我写了一些带有空格和另一个字符的东西,例如"hello world",窗口就会关闭。
我的代码是:
set /p append=Write what you want to append:
然后我尝试了:
set /p "append=Write what you want to append: "
我在网上找到的,但它不起作用。
暂停没有任何帮助,因为一旦我按 Enter 键,程序就会崩溃。
帮助!
以下是完整的代码:
:append
set /p "append=Write what you want to append: "
if %append%==return (
cls
goto start
)
echo %append% >> %filename%
goto append
:override
cls
echo Name: %filename%
set /p override="Write new content: "
echo %override% > %filename%
pause
cls
goto start
:writefile
echo.
set /p filename=Write file name.extension:
choice /c AO /m "Append to file or override? "
if %ERRORLEVEL%==1 (
cls
echo Name: %filename%
goto append
) else (
goto override
)
每当提示批处理文件的用户输入set /P
字符串
- 按RETURN或ENTER即可输入任何内容,如果之前未定义环境变量,则在提示后仍未定义环境变量,或者如果之前已定义变量,则变量保留其当前值,或者
- 输入任何内容,包括字符串,该字符串可能导致批处理执行退出,因为稍后批处理代码中的语法错误或不需要的行为。
让我们看看线上
if %append%==return (
如果之前未使用默认值定义环境变量,并且批处理用户未输入任何内容,则此行将在预处理步骤期间扩展为:
if ==return (
此命令行当然是无效的,并且由于语法错误而导致批处理退出。
现在让我们假设用户输入字符串:
I want to append this string.
然后IF命令行扩展为:
if I want to append this string.==return (
当然,这个命令行也是无效的。
其他回答者建议将两个字符串括起来,用双引号进行比较,即使用命令行:
if "%append%"=="return" (
但这真的解决了所有可能的问题吗?
现在的代码对任何用户输入是否真的安全。
让我们看看如果用户输入字符串会发生什么:
" is a double quote. It should be used around paths like "%ProgramFiles(x86)%".
IF命令行现在扩展为:
if "" is a double quote. It should be used around paths like "%ProgramFiles(x86)%""=="return" (
并且此命令行再次无效,并由于语法错误导致批处理文件退出。
那么如何使批处理代码对任何用户输入都是安全的呢?
解决方案是在引用用户输入的字符串时使用延迟环境变量扩展。
例:
@echo off
setlocal EnableDelayedExpansion
echo.
echo Enter EXIT to exit this batch script.
:PromptUser
echo.
set "UserInput=Nothing^!"
set /P "UserInput=Please enter a string: "
if /I "!UserInput!" == "exit" goto EndBatch
echo You entered: !UserInput!
goto PromptUser
:EndBatch
echo.
echo Thanks for running this example batch code.
echo.
echo The batch file ends in 3 seconds ...
endlocal
%SystemRoot%System32ping.exe localhost -n 4 >nul
通过使用延迟扩展,用户输入的字符串不会在以后的代码中导致无效或意外的命令行。这对于命令行也很重要
echo !append!>>%filename%
重要的是没有空格字符>>
否则此空格字符也作为尾随空格写入文件。
但是延迟扩展在这里也很重要,以防用户输入,例如2
这会导致echo %append%>>%filename%
echo 2>>%filename%
它不会将字符2
附加到文件,但会将STDERR附加到文件,从而导致向文件写入空行。
用户输入的此字符串也需要延迟扩展:
(Var1 > 0x2F) && (Var1 < 0x3A)
它应该按照输入的ECHO写入文件,而不是 Windows 命令解释器在使用echo %append%>>%filename%
时扩展字符串后会产生的内容。
更改set
以将引号放在提示字符串周围的正确位置,更改if
行以在要测试的字符串周围放置引号。
set /p append="Write what you want: "
set append
echo xx%append%yy
if "%append%"=="return" (
echo Yes!
)
你的问题是
if %append%==return (
如果append
包含空格,这将给出语法错误。
用
if "%append%"=="return" (
"引用字符串"使cmd
将其解释为单个元素,因此所需的语法if
,
if string==string (
不再违反。