【问题标题】:Batch: Show last user input批处理:显示最后的用户输入
【发布时间】:2017-12-11 11:39:30
【问题描述】:

(这是我在这里的第一篇文章,请多多包涵)

你能在批处理文件中显示最后的用户输入吗?我会尽量保持简单。

@echo off

:menu
echo Type 1 to proceed.
set /p example=
if "%example%" == "1" GOTO :proceed
GOTO :error

:proceed
pause

:error
cls
echo You wrote (last user input), that's not correct.
timeout 30
GOTO :menu

我知道我可以用 %example% 替换(最后一个用户输入),但是我必须为每个类别制作自定义错误消息,其中大约有 50 个。最后输入命令会更容易。

顺便说一句,我已经自学了关于批处理的所有知识,所以我的示例现在可能存在重大问题,但它以某种方式起作用。

【问题讨论】:

    标签: batch-file batch-processing


    【解决方案1】:

    如果没有临时文件,我不知道该怎么做。要将内容写入控制台,您需要doskey /history(这将跳过脚本本身的运行):

    @echo off
    setlocal enableDelayedExpansion
    set "last="
    set "but_last="
    doskey /history > log.txt
    for /f "tokens=* delims=" %%# in (log.txt) do (
        set "but_last=!last!"
        set "last=%%#"
    )
    
    echo "%but_last%"
    del /s /q log.txt >nul 2>nul
    

    【讨论】:

    • 很好的解决方案,但可能有点矫枉过正:-)
    【解决方案2】:

    您可以将所有用户输入集中到一个函数中(user_input)

    :menu1
    echo Type 1 to proceed.
    call :userInput example
    if "%example%" == "1" GOTO :proceed
    GOTO :error
    
    :menu2
    echo Type 42 to proceed.
    call :userInput answer
    if "%answer%" == "42" GOTO :proceed
    GOTO :error
    
    :userInput
    set /p LAST_INPUT=
    set "%1=%LAST_INPUT%"
    exit /b
    
    :proceed
    pause
    
    :error
    cls
    echo You wrote "%LAST_INPUT%", that's not correct.
    timeout 30
    GOTO :menu
    

    【讨论】:

    • 是的。这样更好。+1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-22
    相关资源
    最近更新 更多