Can I declare a list or array in a batch file like this:
set list = "A B C D"
And then I need to write these to a file, with the spaces between:
A B C D
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.
Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.
&& runs the second command on the line when the first command comes back successfully (i.e. errorlevel == 0 ). The opposite of && is || , which runs the second command when the first command is unsuccessful (i.e. errorlevel != 0 ).
When used in a command line, script, or batch file, %1 is used to represent a variable or matched string. For example, in a Microsoft batch file, %1 can print what is entered after the batch file name.
Yes, you may use both ways. If you just want to separate the elements and show they in separated lines, a list is simpler:
set list=A B C D
A list of values separated by space may be easily processed by for
command:
(for %%a in (%list%) do ( echo %%a echo/ )) > theFile.txt
You may also create an array this way:
setlocal EnableDelayedExpansion set n=0 for %%a in (A B C D) do ( set vector[!n!]=%%a set /A n+=1 )
and show the array elements this way:
(for /L %%i in (0,1,3) do ( echo !vector[%%i]! echo/ )) > theFile.txt
For further details about array management in Batch files, see: Arrays, linked lists and other data structures in cmd.exe (batch) script
ATTENTION! You must know that all characters included in set
command are inserted in the variable name (at left of equal sign), or in the variable value. For example, this command:
set list = "A B C D"
create a variable called list
(list-space) with the value "A B C D"
(space, quote, A, etc). For this reason, it is a good idea to never insert spaces in set
commands. If you need to enclose the value in quotes, you must enclose both the variable name and its value:
set "list=A B C D"
PS - You should NOT use ECHO.
in order to left blank lines! An alternative is ECHO/
. For further details about this point, see: http://www.dostips.com/forum/viewtopic.php?f=3&t=774
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With