Search code examples
variablesbatch-filebatch-choice

Variables in batch


I am trying to create a code that can process a variable based on a choice in a way like this:

set item1=ring
set item2=deadhead
set item3=bloodstainedmap
set item4=strangebox
cls
echo 1) %item1%
echo 2) %item2%
echo 3) %item3%
echo 4) %item4%
echo. 
echo Which Item do you wish to look at?
choice /c 1234 /n >nul
if %errorlevel%==1 goto itemin
if %errorlevel%==2 goto itemin
if %errorlevel%==3 goto itemin
if %errorlevel%==4 goto itemin

:itemin
cls
echo %item%errorlevel%%
::^^^^ this part here should read "ring" if i selected 1. It reads "errorlevel"

Obviously, I would like the Item to shown correctly when it loads the variable....

Any help?

A.S.C


Solution

  • Here is my suggestion for this task:

    @echo off
    setlocal EnableExtensions DisableDelayedExpansion
    set "item1=ring"
    set "item2=deadhead"
    set "item3=bloodstainedmap"
    set "item4=strangebox"
    cls
    echo 1) %item1%
    echo 2) %item2%
    echo 3) %item3%
    echo 4) %item4%
    echo(
    setlocal EnableDelayedExpansion
    :UserChoice
    %SystemRoot%\System32\choice.exe /C 1234 /N /M "Which item do you wish to look at?"
    if not errorlevel 1 goto UserChoice
    set "item=!item%ERRORLEVEL%!"
    endlocal & set "item=%item%"
    echo %item%
    endlocal
    

    The user prompt is repeated if the user presses Ctrl+C and answers the prompt by cmd.exe to exit processing of the batch file with N in which case the condition if not errorlevel 1 is true as the exit code of CHOICE is 0 in this special use case.

    It would be of course also possible to enable delayed expansion already at top of the batch file. It must be just taken into account that all lines are parsed twice on doing that and ! is interpreted everywhere as start/end of a delayed expanded environment variable reference.

    To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.

    • choice /?
    • cls /?
    • echo /?
    • endlocal /?
    • if /?
    • set /?
    • setlocal /?

    See also: