0

I have this code here simply trying to create a file that the name is chosen from a randomized array. Why does it output incorrectly?

Code:

@echo off

set i=0
for %%a in (Cow Dog Bird Fish Meerkat Cat) do (
   set /A i+=1
   set operator[!i!]=%%a
)
set /a operator=%random%%%4+1
set operator=!operator[%operator%]!

copy /y NUL %operator%>NUL

The file created is titled something like !operator[3]! instead of one of the strings in the array. Why is this the case? Any help is appreciated!

Excallypurr
  • 319
  • 1
  • 16
  • 2
    add [`setlocal enabledelayedexpansion`](https://ss64.com/nt/delayedexpansion.html) to the top. – Alex K. Mar 21 '18 at 15:45
  • 1
    @Excallypurr, you are your own worst enemy. You need to use the code examples you have been given as they were provided and heed the extra advice people are giving you. – Squashman Mar 21 '18 at 16:34
  • I only have a basic understanding of what `setlocal enableddelayedexpansion` does. Therefor I do not know when or how it should be used, that's why I asked this question. With Alex K's answer and dbenham's I have a better understanding of that although still limited. I have incorporated the `%%i` suggestion as well in my code. I am trying to learn as much as I can. – Excallypurr Mar 21 '18 at 19:10
  • @Excallypurr, delayed expansion was explained to you a few times in your previous questions. – Squashman Mar 21 '18 at 19:40
  • Generally speaking, always use it. – SomethingDark Mar 22 '18 at 01:55
  • @Excallypurr, in [this previous question](https://stackoverflow.com/questions/49355707/why-wont-my-for-loop-using-random-work-in-batch) you said: _"For some reason that I don't know, this code does not output correctly"_, and I replied: _"The 'some reason' because your code does not work is the modifications you introduced in such a code"_... – Aacini Mar 22 '18 at 01:55
  • Will there ever be a case where using it will cause issues @SomethingDark? – Excallypurr Mar 22 '18 at 06:10
  • If you're trying to run the script on something earlier than XP, delayed expansion won't exist, but that's really the only reason to ever not use it. – SomethingDark Mar 22 '18 at 07:36

1 Answers1

2

Alex K identified your primary problem in his comment - you are missing setlocal enableDelayedExpansion.

But you have another problem - your array contains 6 values, but you are randomly selecting an index between 1 and 4 instead of between 1 and 6.

You should use set /a operator=%random%%%i+1. Note that true environment variables do not need to be expanded when used with SET /A.

dbenham
  • 127,446
  • 28
  • 251
  • 390