How do I loop through ASCII values (here, alphabets) and work on them?
I want to echo A to Z without having to type every character manually like
for %%J in (
Surprisingly, there is a solution that makes use of an undocumented built-in environment variable named =ExitCodeAscii
, which holds the ASCII character of the current exit code1 (ErrorLevel
):
@echo off
for /L %%A in (65,1,90) do (
cmd /C exit %%A
call echo %%^=ExitCodeAscii%%
)
The for /L
loop walks through the (decimal) character codes of A
to Z
. cmd /C exit %%A
sets the return code (ErrorLevel
) to the currently iterated code, which is echo
-ed as a character afterwards. call
, together with the double-%
-signs introduce a second parsing phase for the command line in order to get the current value of =ExitCodeAscii
rather than the one present before the entire for /L
loop is executed (this would happen with a simple command line like echo %=ExitCodeAscii%
). Alternatively, delayed expansion could be used also.
The basic idea is credited to rojo and applied in this post: How do i get a random letter output in batch.
1) The exit code (or return code) is not necessarily the same thing as the ErrorLevel
value. However, the command line cmd /C exit 1
sets both values to 1
. To ensure that the exit code equals ErrorLevel
, use something like cmd /C exit %ErrorLevel%
.