On 2026-10-22 at 09:37, Franco Martelli wrote: > On 21/10/26 at 21:04, Greg Wooledge wrote:
>> Otherwise, you can use a function like this one from FAQ 26:
>>
>> rand() {
>> local max=$((32768 / $1 * $1))
>> while (( (r=RANDOM) >= max )); do :; done
>> r=$(( r % $1 ))
>> }
>>
>> You'd use it like this:
>>
>> clips=(...)
>> n=${#clips[@]}
>> declare -A chosen
>> playlist=()
>>
>> for i in {1..10}; do
>> # Get an unused clip, which may take several tries.
>> while true; do
>> rand "$n" # Get a clip index number in global variable r.
>> [[ ${chosen[$r]} ]] && continue
>>
>> # If we get to this point, it's a new one.
>> chosen[r]=1
>> playlist+=( "${clips[r]}" )
>> break
>> done
>> done
>
> $i isn't used inside the loop, I would expect an ((i++)) at the bottom
> of the "for i in {1..10}; do" loop
That isn't necessary.
As you can see by running
$ echo {1..10}
, the 'for i in {1..10}; do' is exactly equivalent to 'for i in 1 2 3 4
5 6 7 8 9 10 ; do'.
What that tells bash is "for the first item in this list, execute the
contents of this script block; then for the second item in the list,
execute the contents of this script block; then for the third item in
the list, ..." et cetera. The 'for' loop advances from one item in the
provided list to the next, automatically; there's no need for the script
to increment the variable explicitly, the way there would be with a
while loop.
In fact, *because* the value of 'i' is not referenced within the loop,
I'm reasonably certain that you could do 'for i in {a..j}; do' with
exactly the same result. What matters is that there are exactly 10 items
in the resulting list, not what those items are.
You could even do 'for i in cat dog mouse rat squirrel bee grasshopper
spider ant bird; do', and unless there's something I'm missing, it would
work just as well. The only advantage of {1..10} or {a..j}, as far as
I'm aware, is that it's shorter and easier to type. (Well, the former
case also makes it visible at a glance how many iterations will be in
the list, where the others require a bit more attention to see that.)
--
The Wanderer
The reasonable man adapts himself to the world; the unreasonable one
persists in trying to adapt the world to himself. Therefore all
progress depends on the unreasonable man. -- George Bernard Shaw
signature.asc
Description: OpenPGP digital signature

