batch-filevariablesstring-length

Getting length of a variable in batch


Suppose I write this batch code to make a variable

set var1=test

Now how would I get the length of this variable and echo it?


Solution

  • If you echo the variable to a file and then get the length of the file, you can subtract 2 characters because of invisible characters.

    echo %var1%> length.txt
    for %%? in (length.txt) do ( set /a length=%%~z? - 2 )
    

    Then your length should be in a variable called "length"