Search code examples
windowsvariablesbatch-filelimitmaxlength

How to limit a batch variable's length


Is it any way to limit the length of a batch variable? I mean, if it is possible to program a variable that only admits between 0 and x characters? So, for an instance, if I entered 123456 and the max length was 4 it wouldn't proceed to continue. I hope you can understand my question. Thanks in advance.


Solution

  • Demonstration batch code according to suggestions of aschipfl and rojo:

    @echo off
    setlocal EnableExtensions EnableDelayedExpansion
    :UserPrompt
    cls
    set "UserInput="
    set /P "UserInput=Enter string with a length between 1 and 4: "
    if not defined UserInput goto UserPrompt
    if not "!UserInput:~4!" == "" goto UserPrompt
    echo/
    echo String entered: !UserInput!
    echo/
    endlocal
    pause
    

    !UserInput:~4! is replaced by command processor on execution of the batch file by the string from user input starting with fifth character. First character of a string value has index value 0 which is reason for number 4 for fifth character. This string is empty if user entered a string not longer than 4 characters, otherwise this substring is not empty resulting in user must input again a string.

    Delayed expansion is used to avoid an exit of batch processing caused by a syntax error if the user enters a string containing an odd number of double quotes.

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

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