Arrays, linked lists and other data structures in cmd.exe (batch) script

batch file multidimensional array
batch file loop through array of strings
batch array index
batch file arrays
arrays in dos batch
batch script split string into array
pass array to batch file
batch script hash table

I was playing with cmd.exe, but in its help I didn't find any info, how to define arrays.

I have found, how to define simple variables:

set a=10
echo %a%

But, I want to create arrays, linked list etc...

So, does it able in cmd.exe ( I mean: does in cmd.exe exist any array keywords? )

I want to realize some algorithms as:

  • bubble sort
  • quick sort
  • gnome sort

etc...

So, I also want to know, does Cmd.exe have references or instances, structs etc?

Cause its help not full in: /?

Could Cmd.exe be defined as full by Turing-Machine definition? ( Turing-Complete )

Ok. I'll try to be as clear as possible to not be misunderstood...

In Windows Batch files a variable name should begin with a letter and may include any valid character, where valid characters are: #$'()*+,-.?@[]_`{}~ besides letters and digits.

This means that from the cmd.exe point of view, SET NORMAL_NAME=123 is exactly the same as SET A#$'()*+,-.?@[\]_{}~=123 and also the same as SET VECTOR[1]=123; all three are normal variables. This way, it is up to you to write variable names in the form of array elements:

set elem[1]=First element
set elem[2]=Second one
set elem[3]=The third one

This way, echo %elem[2]% will show Second one.

If you want to use another variable as index, you must know that the replacement of variables enclosed in percent symbols by their values is parsed from left to right; this means that:

set i=2
echo %elem[%i%]%

doesn't give the desired result because it means: show the value of the elem[ variable, followed by i, followed by the value of the ] variable.

To solve this problem you must use Delayed Expansion, that is, insert setlocal EnableDelayedExpansion command at the beginning, enclose index variables in percent symbols, and enclose the array elements in exclamation marks:

setlocal EnableDelayedExpansion
set elem[1]=First element
set elem[2]=Second one
set elem[3]=The third one
set i=2
echo !elem[%i%]!

You may also use parameters of FOR commands as indexes: for /L %%i in (1,1,3) do echo !elem[%%i]!. You must use !index! to store values in array elements when the index is changed inside a FOR or IF: set elem[!index!]=New value. To get the value of an element when the index changes inside FOR/IF, enclose the element in double percent symbols and precede the command with call. For example, to move a range of array elements four places to the left:

for /L %%i in (%start%,1,%end%) do (
   set /A j=%%i + 4
   call set elem[%%i]=%%elem[!j!]%%
)

Another way to achieve the previous process is to use an additional FOR command to change the delayed expansion of the index by an equivalent replaceable parameter, and then use the delayed expansion for the array element. This method runs faster than previous CALL:

for /L %%i in (%start%,1,%end%) do (
   set /A j=%%i + 4
   for %%j in (!j!) do set elem[%%i]=!elem[%%j]!
)

This way, the Batch file behaves like it manages arrays. I think the important point here is not to discuss if Batch manages arrays or not, but the fact that you may manage arrays in Batch files in an equivalent way of other programming languages.

@echo off
setlocal EnableDelayedExpansion

rem Create vector with names of days
set i=0
for %%d in (Sunday Monday Tuesday Wednesday Thrusday Friday Saturday) do (
   set /A i=i+1
   set day[!i!]=%%d
)

rem Get current date and calculate DayOfWeek
for /F "tokens=1-3 delims=/" %%a in ("%date%") do (
   set /A mm=10%%a %% 100, dd=10%%b %% 100, yy=%%c
)
if %mm% lss 3 set /A mm=mm+12, yy=yy-1
set /A a=yy/100, b=a/4, c=2-a+b, e=36525*(yy+4716)/100, f=306*(mm+1)/10, jdn=c+dd+e+f-1523, dow=jdn %% 7 + 1
echo Today is !day[%dow%]!, %date%

Note that index values are not limited to numbers, but they may be any string that contain valid characters; this point allows to define what in other programming languages are called associative arrays. At this answer there is a detailed explanation of the method used to solve a problem using an associative array. Note also that the space is a valid character in variable names, so you must pay attention to not insert spaces in variable names that may go unnoticed.

I elaborated on the reasons I have to use array notation in Batch files at this post.

In this post there is a Batch file that reads a text file and stores the indexes of the lines in a vector, then does a Buble Sort of vector elements based on line contents; the equivalent result is a sort over file contents.

In this post there is a basic Relational Data Base application in Batch based on indexes stored in files.

In this post there is a complete multiple linked-list application in Batch that assembles a large data structure taken from a subdirectory and displays it in the form of TREE command.

Arrays, structures and linked lists in Batch files, for "Arrays, linked lists and other data structures in Batch scripts". SET /A command to directly process array element values with no need of  Arrays are not specifically defined as a type in Batch Script but can be implemented. The following things need to be noted when arrays are implemented in Batch Script. Each element of the array needs to be defined with the set command. The ‘for’ loop would be required to iterate through the values of the array.

Windows shell scripting really isn't designed to work with arrays, let alone complex data structures. For the most part, everything's a string in the windows shell, but, there are some things you can do to "work with" arrays, like declaring n variables VAR_1, VAR_2, VAR_3... using a loop and filtering on the prefix VAR_, or creating a delimited string and then using the FOR construct that iterates over a delimited string.

Similarly, you can use the same basic idea to create a struct-like set of variables like ITEM_NAME, ITEM_DATA or w/e. I even found this link that talks about simulating an associative array in CMD.

It is all terribly hackish and inconvenient when it comes down to it. The command-line shell just wasn't designed for heavy programming. I agree with @MatteoItalia -- if you need serious scripting, use a real scripting language.

Arrays, linked lists and other data structures in cmd.exe (batch) script, Arrays, linked lists and other data structures in cmd.exe (batch) script. batch file multidimensional array a in batch file batch file iterate through array arrays in dos​  Windows shell scripting really isn't designed to work with arrays, let alone complex data structures. For the most part, everything's a string in the windows shell, but, there are some things you can do to "work with" arrays, like declaring n variables VAR_1, VAR_2, VAR_3 using a loop and filtering on the prefix VAR_, or creating a delimited string and then using the FOR construct that

I made a bubble sort implementation in batch using pseudo-arrays a while ago. Not sure why you'd use it (although I will admit to doing so in another batch file) as it gets pretty slow as the list size increases. It was more to set myself a little challenge. Someone might find this useful.

:: Bubblesort
:: Horribly inefficient for large lists
:: Dave Johnson implementation 05/04/2013
@echo off
setlocal enabledelayedexpansion
:: Number of entries to populate and sort
set maxvalue=50
:: Fill a list of vars with Random numbers and print them
for /l %%a in (1,1,%maxvalue%) do (
    set /a tosort%%a=!random!
)
:: echo them
set tosort
:: Commence bubble sort
Echo Sorting...
set /a maxvalue-=1
set iterations=0
for /l %%a in (%maxvalue%,-1,1) do ( REM Decrease by 1 the number of checks each time as the top value will always float to the end
    set hasswapped=0
        for /l %%b in (1,1,%%a) do (
            set /a next=%%b+1
            set next=tosort!next!
            set next=!next!
            call :grabvalues tosort%%b !next!
            rem echo comparing tosort%%b = !tosortvalue! and !next! = !nextvalue!
            if !nextvalue! LSS !tosortvalue! (
            rem set /a num_of_swaps+=1
            rem echo Swapping !num_of_swaps!
                set !next!=!tosortvalue!
                set tosort%%b=!nextvalue!
                set /a hasswapped+=1
            )
        )
    set /a iterations+=1
    if !hasswapped!==0 goto sorted
)
goto:eof
:grabvalues
set tosortvalue=!%1!
set nextvalue=!%2!
goto:eof
:sorted
::nice one our kid
set tosortvalue=
echo Iterations required: %iterations%
set tosort
endlocal

Creating a List or Arrays in Windows Batch, For more information about managing arrays in batch files, see Arrays, linked lists​, and other data structures in the cmd.exe (batch) script. ATTENTION! Arrays. Arrays can be Arrays, linked lists and other data structures in cmd.exe (batch) script, stackoverflow.com; Found a mistake? Have a question or improvement

Seriously speaking: I never heard that batch has arrays, maybe you can emulate them with some strange trick, but I wouldn't call it a good idea.

References/instances/structs are stuff for a real language, cmd scripting is just a bunch of extensions that grew over the very primitive interpreter that was command.com, you can do some basic scripting, but anything more complicated than a bunch of calls to other commands is doomed to become ugly and incomprehensible.

The only "advanced" construct is the do-it-all weirdo for loop, which, mixed with the strange "rules" of variable substitution (%var%, %%var, !var!, are different stuff because of the idiotic parser), makes writing even trivial algorithms a collection of strange hacks (see e.g. here for an implementation of quicksort).

My tip is, if you want to do your scripting in a sane way, use a real scripting language, and leave batch for simple, quick hacks and for backwards compatibility.

Essential Batch / Arrays, Arrays, linked lists and other data structures in cmd.exe (batch) script, stackoverflow.com. Found a mistake? Have a question or improvement idea? Let me know  I suggest you to review: arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script – Aacini Dec 5 '13 at 1:02 add a comment | 3 Answers 3

Concerning this statement:

I have found, how to define simple variables:

set a = 10
echo %a%

This is simply wrong! Variable a will remain empty (supposing it was empty initially) and echo %a% will return ECHO is on. A variable called aSPACE will actually be set to the value SPACE10.

So for the code to work, you must get rid of the SPACEs around the equal-to sign:

set a=10
echo %a%

To make the assignment safe against all characters, use the quoted syntax (supposing you have the command extensions enabled, which is the default for the Windows command prompt anyway):

set "a=1&0"
echo(%a%

For all the rest of your question I recommend to read Aacini's great and comprehensive answer.

Use array to create string in DOS, /arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script REM start the command string with a reference to closure compiler set command=java​  2- structures and linked lists in batch files The Batch file below simulate structures and linked-list management. The program use such simulations to traverse through the directory tree of a given subdirectory and assemble a complex data scheme that include multiple linked lists comprised of these self-referential structures:

Return 'dir' command results into array/list, I want to know how to return the output of the dir command into an array. in a batch file Arrays, linked lists and other data structures in cmd.exe (batch) script  How to Use Array in Windows Batch Programming?We have to define variables using set and the length has to defined first. The above script will print A, B, C in three lines and we treat obj[0], obj[1] and obj[2] as three individual variables (their memory address locations are not continuous).

PC Mag, Unlike other profilers, this one is interactive with pull-downs, pop-ups, and aspects of program execution and walk through data structures, arrays, and linked lists. Unlike other profilers, which are run in batch mode from the command line,  Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question. Provide details and share your research! But avoid … Asking for help, clarification, or responding to other answers. Making statements based on opinion; back them up with references or personal experience. To learn more, see our tips on writing great

batch names list with meaning, Batch files, see: Arrays, linked lists and other data structures in cmd.exe (batch) script Batch scripts support the concept of command line arguments wherein  Tableaux, listes liées et autres structures de données dans cmd.exe (lot) script je jouais avec cmd.exe, mais dans son aide je n'ai pas trouvé d'info, comment définir les tableaux. j'ai trouvé, comment définir des variables simples:

Comments
  • @MatteoItalia linux shell has it, powershell ( based on .net ) has it, don't know about Windows CScript.exe, does it have or not?
  • This should be funny, but it is really sad instead: most answers got 13 upvotes in despite they did NOT answered the question. In my opinion, an answer that just criticize the topic with words like "idiotic", "terribly hackish", "bizarre" and similar terms have not any value at all. Note that I am NOT criticizing that answers nor defending Batch. I just can't see what is the supposed merit of that answers to deserve such amount of upvotes! I wonder if similar criticizing answers to Power Shell, VBS scripts, Phyton, Ruby, Pearl, PHP etc. topics would receive similar amount of upvotes... :(
  • Well said, Aacini. It's important to remember that questions like this cover many simpler use cases that are difficult to find answers for, your response answered several of my questions in the original spirit of SO.
  • @meagar: I don't understand what you mean... I know that all of these programming languages are very different and that each one have its own application area, followers, criticisms, etc., but all of them should deserve some respect from a community of scientists (programmers). However, in this site the criticisms on Batch files are very frequent when compared vs. criticism on other programming languages. Worst of all is that frequently such criticisms are upvoted, so I just wonder: why? Perhaps people that don't like Batch files are more numerous, or less respectful, than the rest...
  • @Aacini: So someone disagreed with you; how shocking! You'll find that this happens frequently in life. Especially when you hold a minority opinion. So you think Batch is a lovely language. Great! You're entitled to that opinion. Other people are entitled to think that it is not. You don't need to panic.
  • Shameless self-promotion: this answer demonstrates a batch implementation of Array.splice() (which also relies on your recommended array[n] naming convention).
  • What do yo mean under serious? Could cmd.exe be defined as full by Turing Machine definition?
  • @magesi CMD does have ONE thing going for it -- the FOR command. If you really want to learn CMD, master that and move on.
  • @trutheality or there ie a way to write own cmd.exe based on NT4 sources, which are able :) And include some new features to it :)
  • @trutheality thanks! :) If I put here the result , may I call you to look at it? :)
  • @magesi: a more useful but crazy enough work would be to reverse-engineer every strange bit of batch syntax (I don't think there's an official specification even at Microsoft) and fix up the cmd.exe from the Wine project. :)
  • Excuse me. I don't like your "pseudo-arrays" reference. An array is mainly a concept: a set of elements with same name that are selected via an index. Your program may manage an array or may not; there is not such "pseudo-array" thing. See my previous link for further details...