🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Thread View: linux.debian.user
34 messages
34 total messages Started by Franco Martelli Wed, 21 Oct 2026 14:50
Bash: check if a value is into an array
#218
Author: Franco Martelli
Date: Wed, 21 Oct 2026 14:50
34 lines
4570 bytes
Hi,

I run into issue trying to populate an array with unique random value, 
the issue is that I have an endless loop, here the snippet:

...
# Populate playlist array with unique random values
while [ "$index" -le "$total" ]; do
         clip="$(/usr/bin/numrandom /1..$total/)"
         if [[ ! ${playlist[@]} =~ "$clip" ]]; then      # [ -z 
${rndarr[clip]} ]; then
                                                         # rndarr[$clip]=1
                playlist[$index]=$clip
                ((index++))
         fi
done
...

It works fine if I use the second array "rndarr[]". I use that array to 
store 1 at the rndarr[$index] occurrence then, after incremented the 
index, I check whether it's empty (no 1 stored) at the new $index value.

My wishes is to avoid to use a second array (rndarr[]) and use 
playlist[] array only to do this, but with the above code I have an 
endless loop, why?

I checked the remarkable ABS ¹ handbook at chapter 27 but nothing helped 
about finding values inside an array (only replacement examples).

Thanks in advance for any hint, kind regards,

¹ https://tldp.org/LDP/abs/abs-guide.pdf
-- 
Franco Martelli
Re: Bash: check if a value is into an array
#222
Author: Greg Wooledge
Date: Wed, 21 Oct 2026 15:10
86 lines
5074 bytes
On Wed, Oct 21, 2026 at 16:45:30 +0200, Franco Martelli wrote:
> # Populate playlist array with unique random values
> while [ "$index" -le "$total" ]; do
>         clip="$(/usr/bin/numrandom /1..$total/)"

I would try to avoid calling an external program inside this loop,
especially if the purpose of the external program is just to choose
a random number between 1 and n.  That can be done with a non-forking
bash function call.

>         if [[ ! ${playlist[@]} =~ "$clip" ]]; then      # [ -z
> ${rndarr[clip]} ]; then
>                                                         # rndarr[$clip]=1
>                playlist[$index]=$clip
>                ((index++))
>         fi
> done

> It works fine if I use the second array "rndarr[]". I use that array to
> store 1 at the rndarr[$index] occurrence then, after incremented the index,
> I check whether it's empty (no 1 stored) at the new $index value.
> 
> My wishes is to avoid to use a second array (rndarr[]) and use playlist[]
> array only to do this, but with the above code I have an endless loop, why?

OK, first note: using an associative array would be the typical way to
store a set of "things that have already been chosen".  Your "rndarr"
seems to be an indexed array, which I guess will also work as long
as the "thing chosen" is a non-negative integer.

Trying to do this without a second array means you need to search through
the entire first array every time to see whether the thing is already
in the array.  That's an O(n) operation, while looking for an element
in an associative array (or your second indexed array) should be a much
faster O(1) operation.

Second note:  [[ ! ${x[@]} =~ "$i" ]]  is not even a safe way to check
for the existence of an element "$i" in an array "x".  Consider the
case where i = 5, and you've got 15 and 50 already in the array.  The
expansion of ${x[@]} will include the text "15 50", and doing an =~ 5
against that text will yield a false positive.

Third note: many people, at this point, will cobble together some code
like this:

    IFS=:
    [[ ":${x[*]}:" =~ ":$i:" ]] ...
    unset IFS

which compares the string :15:50: against the regex :5:.  This works,
sort of.  But you're expanding the *entire* array as a string on
every single loop iteration, generating a regular expression and
applying it... it's overkill.  You can reduce the regular expression
to a substring match:

    IFS=:
    [[ ":${x[*]}:" = *":$i:"* ]] ...
    unset IFS
    
which is slightly better, but you're still copying the entire array
every single iteration.

Fourth note: if you want to check whether $i is in the array x[],
the proper way is to *use a loop*:

    found=0
    for element in "${x[@]}"; do
        if [[ $element = "$i" ]]; then
            found=1
            break
        fi
    done

This avoids copying the entire array, and it allows you to stop early
once you find the element.

Honestly, I would just use the associative array.  It'll be much more
efficient than anything else you can do.

Fifth note: you want to know why your loop never terminates, but I
can't give you an answer to that.  I'd suggest turning on set -x to
see what the script is doing.

> I checked the remarkable ABS ¹ handbook

The most remarkable thing about the ABS is how many flaws it contains.
Re: Bash: check if a value is into an array
#231
Author: Franco Martelli
Date: Wed, 21 Oct 2026 18:40
155 lines
9534 bytes
On 21/10/26 at 17:07, Greg Wooledge wrote:
> On Wed, Oct 21, 2026 at 16:45:30 +0200, Franco Martelli wrote:
>> # Populate playlist array with unique random values
>> while [ "$index" -le "$total" ]; do
>>          clip="$(/usr/bin/numrandom /1..$total/)"
> 
> I would try to avoid calling an external program inside this loop,
> especially if the purpose of the external program is just to choose
> a random number between 1 and n.  That can be done with a non-forking
> bash function call.

First of all thanks Greg for your patience explaining me coding. I'm 
interested about avoid to call an external tool inside the loop, do you 
have a snippet of code that provides random numbers in a specified range 
using a bash function?

> 
>>          if [[ ! ${playlist[@]} =~ "$clip" ]]; then      # [ -z
>> ${rndarr[clip]} ]; then
>>                                                          # rndarr[$clip]=1
>>                 playlist[$index]=$clip
>>                 ((index++))
>>          fi
>> done
> 
>> It works fine if I use the second array "rndarr[]". I use that array to
>> store 1 at the rndarr[$index] occurrence then, after incremented the index,
>> I check whether it's empty (no 1 stored) at the new $index value.
>>
>> My wishes is to avoid to use a second array (rndarr[]) and use playlist[]
>> array only to do this, but with the above code I have an endless loop, why?
> 
> OK, first note: using an associative array would be the typical way to
> store a set of "things that have already been chosen".  Your "rndarr"
> seems to be an indexed array, which I guess will also work as long
> as the "thing chosen" is a non-negative integer.
> 
> Trying to do this without a second array means you need to search through
> the entire first array every time to see whether the thing is already
> in the array.  That's an O(n) operation, while looking for an element
> in an associative array (or your second indexed array) should be a much
> faster O(1) operation.
> 
> Second note:  [[ ! ${x[@]} =~ "$i" ]]  is not even a safe way to check
> for the existence of an element "$i" in an array "x".  Consider the
> case where i = 5, and you've got 15 and 50 already in the array.  The
> expansion of ${x[@]} will include the text "15 50", and doing an =~ 5
> against that text will yield a false positive.

Yes I was afraid of this, but I wasn't sure that it happened.

> 
> Third note: many people, at this point, will cobble together some code
> like this:
> 
>      IFS=:
>      [[ ":${x[*]}:" =~ ":$i:" ]] ...
>      unset IFS
> 
> which compares the string :15:50: against the regex :5:.  This works,
> sort of.  But you're expanding the *entire* array as a string on
> every single loop iteration, generating a regular expression and
> applying it... it's overkill.  You can reduce the regular expression
> to a substring match:
> 
>      IFS=:
>      [[ ":${x[*]}:" = *":$i:"* ]] ...
>      unset IFS
>      
> which is slightly better, but you're still copying the entire array
> every single iteration.
> 
> Fourth note: if you want to check whether $i is in the array x[],
> the proper way is to *use a loop*:
> 
>      found=0
>      for element in "${x[@]}"; do
>          if [[ $element = "$i" ]]; then
>              found=1
>              break
>          fi
>      done
> 
> This avoids copying the entire array, and it allows you to stop early
> once you find the element.
> 
> Honestly, I would just use the associative array.  It'll be much more
> efficient than anything else you can do.

OK, I'll stay with my first version that uses a second array to mark a 
random value as assigned:

...
# Populate playlist array with unique random values
while [ "$index" -le "$total" ]; do
         clip="$(/usr/bin/numrandom /1..$total/)"
         if [ -z ${rndarr[clip]} ]; then
                 rndarr[$clip]=1
                 playlist[$index]=$clip
                 ((index++))
         fi
done
...

~$ time ./rndclips
1 120 93 30 13 104 113 28 18 101 12 131 15 107 109 58 36 75 76 57 64 45 
47 67 19 63 53 116 94 81 59 84 72 4 31 6 51 82 3 122 87 10 89 42 35 54 
90 96 99 38 34 95 16 136 25 5 21 123 80 133 79 66 60 132 39 8 11 118 49 
22 134 44 29 86 17 14 20 83 9 43 2 105 65 61 23 41 70 37 7 121 110 48 
125 97 73 74 27 108 68 78 103 69 50 126 106 119 62 1 88 135 52 114 92 85 
55 100 111 46 26 124 77 98 102 33 117 112 56 129 71 130 24 91 32 40 128 
115 127

real    0m5,228s
user    0m3,922s
sys     0m1,350s

This works, that was the time it takes to populate an array of 137 
elements. But it still suffers to fork a sub-process much more times of 
137 iterations.

> 
> Fifth note: you want to know why your loop never terminates, but I
> can't give you an answer to that.  I'd suggest turning on set -x to
> see what the script is doing.

I prefer to not investigate because traverse an entire array for each 
iteration it is not the right things to do (I changed my mind).

> 
>> I checked the remarkable ABS ¹ handbook
> 
> The most remarkable thing about the ABS is how many flaws it contains.

:) but I learnt my Bash scripting reading ABS and I suppose I'm not 
alone, for instance at page #431 :
...
# Substring Replacement
# Replace first occurrence of substring with replacement.
echo ${arrayZ[@]/fiv/XYZ} # one two three four XYZe XYZe
#               ^         # Applied to all elements of the array.
...

This made me thinking that there was a standard way to query the array 
for a value.

You talked me about a Bash function able to return a random value 
between 1 and n, at page #107 of the ABS I see that I have to use the 
'modulo' operator to apply a range to a variable assigned with $RANDOM 
but it doesn't explain how to start from 1 and not from 0. Do I have to 
accept ranges from 0 to n and then discard the 0?

Kind regards,
-- 
Franco Martelli
Re: Bash: check if a value is into an array
#232
Author: Nicolas George
Date: Wed, 21 Oct 2026 18:50
19 lines
2969 bytes
Franco Martelli (HE12026-10-21):
> a snippet of code that provides random numbers in a specified range using a
> bash function?

man bash
/random

The answer is immediate.

By the way, it seems what you want is not just distinct elements but all
the elements too: a permutation. For that, there is a much more
efficient algorithm: swap the first element randomly with any of the
elements, then the second with any of the elements except the first,
etc.

Regards,

-- 
  Nicolas George
Re: Bash: check if a value is into an array
#234
Author: Greg Wooledge
Date: Wed, 21 Oct 2026 19:10
14 lines
2636 bytes
On Wed, Oct 21, 2026 at 20:48:28 +0200, Nicolas George wrote:
> By the way, it seems what you want is not just distinct elements but all
> the elements too: a permutation. For that, there is a much more
> efficient algorithm: swap the first element randomly with any of the
> elements, then the second with any of the elements except the first,
> etc.

I didn't get that impression from his code, but if he really does want
his playlist to be the same size, or nearly the same size, as his
full library of selections, then shuffling the array is the way to go
for sure.

You don't want to be in a situation where you're generating random
numbers waiting for that last song out of 10,000 songs to be chosen.
Re: Bash: check if a value is into an array
#235
Author: Greg Wooledge
Date: Wed, 21 Oct 2026 19:10
69 lines
4423 bytes
On Wed, Oct 21, 2026 at 20:30:25 +0200, Franco Martelli wrote:
> First of all thanks Greg for your patience explaining me coding. I'm
> interested about avoid to call an external tool inside the loop, do you have
> a snippet of code that provides random numbers in a specified range using a
> bash function?

https://mywiki.wooledge.org/BashFAQ/026

> You talked me about a Bash function able to return a random value between 1
> and n, at page #107 of the ABS I see that I have to use the 'modulo'
> operator to apply a range to a variable assigned with $RANDOM but it doesn't
> explain how to start from 1 and not from 0. Do I have to accept ranges from
> 0 to n and then discard the 0?

Well, usually you want 0 to n-1 because arrays are indexed from 0.  If
you want 1 to n, you can use something that gives you 0 to n-1, and
then add 1 to it.

Given an array of n elements, if we first store the size in a variable
for convenience:

    n=${#array[@]}

then the *easiest* way to select a random element (0 to n-1) is to use:

    ${array[RANDOM % n]}

But as FAQ 26 explains, this is imperfect.  There is a bias toward the
lower numbers (unless n is an exact divisor of 32768).  So, you have
to decide whether you can live with that bias or not.  For something
that's just generating a playlist of songs, this may be good enough.

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

That generates a "playlist" array with 10 randomly selected, unique
elements from the "clips" array.  I didn't add any sanity checking,
so there are some obvious issues, like an infinite loop if clips
has fewer than 10 elements.  But it should be a decent starting point.

Another algorithm for solving this same problem would be to randomly
shuffle the clips array, and then use the first 10 elements as your
playlist.  I won't include code for that, but you should be able to
do that using the examples in FAQ 26.
Re: Bash: check if a value is into an array
#242
Author: Michel Verdier
Date: Thu, 22 Oct 2026 09:30
15 lines
1880 bytes
On 2026-10-21, Greg Wooledge wrote:

>     IFS=:
>     [[ ":${x[*]}:" =~ ":$i:" ]] ...
>     unset IFS

Would it be safer to restore IFS ?
With something like

  OLDIFS=$IFS
  IFS=:
  ...
  IFS=$OLDIFS

or using local if within a function
Re: Bash: check if a value is into an array
#246
Author: Greg Wooledge
Date: Thu, 22 Oct 2026 12:10
60 lines
3661 bytes
On Thu, Oct 22, 2026 at 11:23:35 +0200, Michel Verdier wrote:
> On 2026-10-21, Greg Wooledge wrote:
> 
> >     IFS=:
> >     [[ ":${x[*]}:" =~ ":$i:" ]] ...
> >     unset IFS
> 
> Would it be safer to restore IFS ?
> With something like
> 
>   OLDIFS=$IFS
>   IFS=:
>   ...
>   IFS=$OLDIFS
> 
> or using local if within a function

Using local is good, yes.  You could even wrap this in a function so
that local becomes available.

Both "unset IFS" and "IFS=$OLDIFS" make assumptions that are not going
to be true universally.  Mine assumes that IFS was originally in its
default state, and that you want to continue being in the default
state afterward.  Unsetting IFS is operationally equivalent to
setting IFS to its default value of $' \t\n' (just easier to type).

Yours assumes that IFS *had* a prior value, and had not been unset.
If IFS was unset beforehand, then IFS=$OLDIFS will assign the empty
string to IFS, which is very different from unsetting it.

So, both of those are potentially wrong, and using local within a
function (even if it's a lambda created just for this purpose) is
definitely the safest approach.

If you ever need to do this sort of thing in POSIX sh, where local is
not yet mandated, saving IFS will need two steps: you'll need to check
whether IFS is currently unset, as well as tracking its current value
(if any).  Then, for the restoration, you will once again need to check
whether you should unset IFS, or restore its previous value.  This
could be done using one variable, or two variables, but either way it
will require at least two separate steps.  This should work:

saveIFS() {
    if test "${IFS+set}"; then
        _ifs=$IFS
    else
        unset _ifs
    fi
}   

restoreIFS() {
    if test "${_ifs+set}"; then
        IFS=$_ifs
    else
        unset IFS
    fi
}

Obviously it can be squeezed into fewer lines, but I wrote it in this
style for clarity.
Re: Bash: check if a value is into an array
#247
Author: tomas
Date: Thu, 22 Oct 2026 13:00
37 lines
2695 bytes
--qtqD/t18Z+KINUuU
Content-Type: text/plain; charset=utf-8
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Thu, Oct 22, 2026 at 08:02:58AM -0400, Greg Wooledge wrote:

[...]

> Both "unset IFS" and "IFS=3D$OLDIFS" make assumptions that are not going
> to be true universally [...]

Greg,

as someone who writes occasionaly shell, and has been doing
that for longer he'd like to admit, I want to thank your for
your posts: always informative, precise, and a pleasure to
read.

There, had to be said.

Cheers
--=20
t

--qtqD/t18Z+KINUuU
Content-Type: application/pgp-signature; name="signature.asc"

-----BEGIN PGP SIGNATURE-----

iF0EABECAB0WIQRp53liolZD6iXhAoIFyCz1etHaRgUCatoGdAAKCRAFyCz1etHa
RmnTAJsHzrknjkIhrYmjGRhZS7BVrT4pcwCfWC5BdMAakJm5kAc9+wQqGfnnQGM=
=VXDB
-----END PGP SIGNATURE-----

--qtqD/t18Z+KINUuU--
Re: Bash: check if a value is into an array
#250
Author: Franco Martelli
Date: Thu, 22 Oct 2026 13:40
127 lines
8011 bytes
On 21/10/26 at 21:04, Greg Wooledge wrote:
> On Wed, Oct 21, 2026 at 20:30:25 +0200, Franco Martelli wrote:
>> First of all thanks Greg for your patience explaining me coding. I'm
>> interested about avoid to call an external tool inside the loop, do you have
>> a snippet of code that provides random numbers in a specified range using a
>> bash function?
> 
> https://mywiki.wooledge.org/BashFAQ/026

Very nice, at the snippet for playing a song or seeing an image:
...
# Bash
files=(*.txt)
n=${#files[@]}
randfile=${files[RANDOM % n]}
...
I would mention that it's possible that a file will be pick twice. It 
needs an array populated with unique random values and then pick the 
"randfile" from "files[]" using that array as index value, see my code 
below.

> 
>> You talked me about a Bash function able to return a random value between 1
>> and n, at page #107 of the ABS I see that I have to use the 'modulo'
>> operator to apply a range to a variable assigned with $RANDOM but it doesn't
>> explain how to start from 1 and not from 0. Do I have to accept ranges from
>> 0 to n and then discard the 0?
> 
> Well, usually you want 0 to n-1 because arrays are indexed from 0.  If
> you want 1 to n, you can use something that gives you 0 to n-1, and
> then add 1 to it.
> 
> Given an array of n elements, if we first store the size in a variable
> for convenience:
> 
>      n=${#array[@]}
> 
> then the *easiest* way to select a random element (0 to n-1) is to use:
> 
>      ${array[RANDOM % n]}
> 
> But as FAQ 26 explains, this is imperfect.  There is a bias toward the
> lower numbers (unless n is an exact divisor of 32768).  So, you have
> to decide whether you can live with that bias or not.  For something
> that's just generating a playlist of songs, this may be good enough.
> 
> 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 generates a "playlist" array with 10 randomly selected, unique
> elements from the "clips" array.  I didn't add any sanity checking,
> so there are some obvious issues, like an infinite loop if clips
> has fewer than 10 elements.  But it should be a decent starting point.
> 
> Another algorithm for solving this same problem would be to randomly
> shuffle the clips array, and then use the first 10 elements as your
> playlist.  I won't include code for that, but you should be able to
> do that using the examples in FAQ 26.

When I write code I try to avoid complexity if not strictly necessary so 
I think I'll go with the following script:

...
#!/bin/bash

cd ~/Video/clips/partyzone/
declare -a rndarr
declare -a playlist
files=([0-9][0-9][0-9][0-9]*)
total=${#files[@]}

index=0
# Populate playlist array with unique random values
while [ "$index" -lt "$total" ]; do
	clip=$((RANDOM % total))
	if [ -z ${rndarr[clip]} ]; then
		rndarr[$clip]=1
		playlist[$index]=$clip
		((index++))
	fi
done

# Trap Ctrl+C to exit immediately so the script doesn't continue past ffplay
trap 'echo -e "\nStopping script..."; exit 130' INT

index=0
while [ "$index" -lt "$total" ]; do
	clip=${files[playlist[index]]}
#	/usr/bin/ffplay -vf "scale=720:576,setdar=720/576" -autoexit -volume 
10 "$clip" >/dev/null 2>&1
	echo $clip
	((index++))
done
...

It's readable enough and simple, thank again,
-- 
Franco Martelli
Re: Bash: check if a value is into an array
#251
Author: Greg Wooledge
Date: Thu, 22 Oct 2026 14:30
135 lines
6255 bytes
On Thu, Oct 22, 2026 at 15:37:09 +0200, Franco Martelli wrote:
> On 21/10/26 at 21:04, Greg Wooledge wrote:
> > https://mywiki.wooledge.org/BashFAQ/026
> 
> Very nice, at the snippet for playing a song or seeing an image:
> ...
> # Bash
> files=(*.txt)
> n=${#files[@]}
> randfile=${files[RANDOM % n]}
> ...
> I would mention that it's possible that a file will be pick twice. It needs
> an array populated with unique random values and then pick the "randfile"
> from "files[]" using that array as index value, see my code below.

You're describing a purpose that the example was not designed to do.
That example just chooses *one* file.  It doesn't loop or anything.
Anyone reading the example and the text above it can immediately see
that if they do this multiple times in a row, they may get the same
file more than once.  That's the nature of random numbers.  It's
obvious and doesn't need to be stated.

> >      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

$i doesn't need to be used.  It's only there to make the loop run 10
times, which the {1..10} already does.  That's bash brace expansion,
and it's equivalent to writing out 1 2 3 4 5 6 7 8 9 10.  The loop could
have been written:

    for i in 1 2 3 4 5 6 7 8 9 10; do
    ...
    done

But {1..10} is shorter.

Incrementing i inside the loop would serve no purpose.  It's already
iterating over a list of 10 strings.  For that matter, the fact that
the strings are numeric doesn't even matter.  It could just as well
have been written:

    for i in alfa bravo charlie delta echo foxtrot golf hotel india juliett; do
    ...
    done

> #!/bin/bash
> 
> cd ~/Video/clips/partyzone/

If this fails, you want to abort, so put || exit at the end of this.

> declare -a rndarr
> declare -a playlist
> files=([0-9][0-9][0-9][0-9]*)
> total=${#files[@]}
> 
> index=0
> # Populate playlist array with unique random values
> while [ "$index" -lt "$total" ]; do
> 	clip=$((RANDOM % total))
> 	if [ -z ${rndarr[clip]} ]; then

This expansion should be quoted.  Or use [[ ]] instead.  Either one's
fine.

> 		rndarr[$clip]=1
> 		playlist[$index]=$clip
> 		((index++))
> 	fi
> done
> 
> # Trap Ctrl+C to exit immediately so the script doesn't continue past ffplay
> trap 'echo -e "\nStopping script..."; exit 130' INT
> 
> index=0
> while [ "$index" -lt "$total" ]; do
> 	clip=${files[playlist[index]]}
> #	/usr/bin/ffplay -vf "scale=720:576,setdar=720/576" -autoexit -volume 10
> "$clip" >/dev/null 2>&1
> 	echo $clip
> 	((index++))
> done

Iterating over the array by index works, but it would be simpler to
iterate over the values instead.

for index in "${playlist[@]}"; do
    clip=${files[index]}
    ffplay -vf ... "$clip"
done

One final note: it looks like you *are* trying to generate a playlist
that contains every single file in your directory.  If the number of
files is small (let's say, 100 or fewer), your approach might be
acceptable, but with larger directories, you're going to spend a long
time waiting for those last few files to be selected.

For this project, it would be better to shuffle the array of files
instead of selecting one at a time.

#!/bin/bash

# Gather the files.
cd ~/Video/clips/partyzone/ || exit
playlist=([0-9][0-9][0-9][0-9]*)

# Shuffle the playlist.
n=${#playlist[@]}
for ((i=n-1; i>0; i--)); do
    max=$(( 32768 / (i+1) * (i+1) ))
    while (( (rand=RANDOM) >= max )); do :; done
    rand=$(( rand % (i+1) ))
    tmp=${playlist[i]} playlist[i]=${playlist[rand]} playlist[rand]=$tmp
done

# Play the shuffled playlist.
for clip in "${playlist[@]}"; do
    ffplay -vf "scale=720:576,setdar=720/576" -autoexit -volume 10 \
        "$clip" >/dev/null 2>&1
done

You can add your trap if you want it.
Re: Bash: check if a value is into an array
#253
Author: CGS
Date: Thu, 22 Oct 2026 15:40
20 lines
3066 bytes
On 2026-10-21, Greg Wooledge <greg@wooledge.org> wrote:
> On Wed, Oct 21, 2026 at 20:48:28 +0200, Nicolas George wrote:
>> By the way, it seems what you want is not just distinct elements but all
>> the elements too: a permutation. For that, there is a much more
>> efficient algorithm: swap the first element randomly with any of the
>> elements, then the second with any of the elements except the first,
>> etc.
>
> I didn't get that impression from his code, but if he really does want
> his playlist to be the same size, or nearly the same size, as his
> full library of selections, then shuffling the array is the way to go
> for sure.
>
> You don't want to be in a situation where you're generating random
> numbers waiting for that last song out of 10,000 songs to be chosen.
>

If I select random on a finite song playlist, I wouldn't want the same song
playing twice; this would require an algorithm that would deselect songs that
have already been chosen. Maybe your code accounted for that (or not).
Re: Bash: check if a value is into an array
#254
Author: Greg Wooledge
Date: Thu, 22 Oct 2026 15:50
24 lines
3171 bytes
On Thu, Oct 22, 2026 at 15:34:59 -0000, CGS wrote:
> If I select random on a finite song playlist, I wouldn't want the same song
> playing twice; this would require an algorithm that would deselect songs that
> have already been chosen. Maybe your code accounted for that (or not).

This is covered by keeping track of what's already been selected,
either in a second array (which is the more efficient way), or by
traversing the playlist to see if the new selection is already in
the playlist (the less efficient way).

With a very small library, this works well enough.  If you have 10
songs, and you generate a playlist by choosing random numbers from
1 to 10 over and over until every number has been selected, it
shouldn't take too long.

With a large library, however, this is very inefficient.  With 10,000
songs, you only have a 1 in 10,000 chance of hitting that final song.
You're going to end up looping hundreds of thousands of times, instead
of only 10,000 times.

If you want a playlist that's as long as your entire library, you should
use a shuffling algorithm instead.  Load up the array, and then make a
single pass through the array, swapping items.  The code to do this is
in my previous message in this thread.
Re: Bash: check if a value is into an array
#255
Author: Max Nikulin
Date: Thu, 22 Oct 2026 16:10
10 lines
3500 bytes
On 22/10/2026 1:48 am, Nicolas George wrote:
> By the way, it seems what you want is not just distinct elements but all
> the elements too: a permutation. For that, there is a much more
> efficient algorithm: swap the first element randomly with any of the
> elements, then the second with any of the elements except the first,
> etc.

shuf(1) or, as it is recommended there,
(info "(coreutils) shuf invocation")
Unless the real goal is to explore BASH arrays.
Re: Bash: check if a value is into an array
#258
Author: Charles Curley
Date: Thu, 22 Oct 2026 17:00
27 lines
4541 bytes
On Thu, 22 Oct 2026 11:43:02 -0400
Greg Wooledge <greg@wooledge.org> wrote:

> On Thu, Oct 22, 2026 at 15:34:59 -0000, CGS wrote:
> > If I select random on a finite song playlist, I wouldn't want the
> > same song playing twice; this would require an algorithm that would
> > deselect songs that have already been chosen. Maybe your code
> > accounted for that (or not).  
> 
> This is covered by keeping track of what's already been selected,
> either in a second array (which is the more efficient way), or by
> traversing the playlist to see if the new selection is already in
> the playlist (the less efficient way).

Another way to prevent repetition is to delete each element from the
array when you play it. This is easy enough to code, but does prevent
you from backtracking.

Another way to get your playlist played randomly and non-repeatably is
to use vlc and have it play randomly within the playlist. I suspect
other players can do similarly.

-- 
Does anybody read signatures any more?

https://charlescurley.com
https://charlescurley.com/blog/
Re: Bash: check if a value is into an array
#260
Author: Franco Martelli
Date: Thu, 22 Oct 2026 17:10
16 lines
4466 bytes
On 22/10/26 at 17:43, Greg Wooledge wrote:
> If you want a playlist that's as long as your entire library, you should
> use a shuffling algorithm instead.  Load up the array, and then make a
> single pass through the array, swapping items.  The code to do this is
> in my previous message in this thread.

Just for the record: and it is also very efficient, I tested it 
measuring the time it takes with my files and it takes half time than my 
code, maybe because it uses a single array to store the filenames and 
then shuffle them.
Save that code or archive the email if you need, in the future, to 
shuffle a playlist or an array of values.

Kind regards,
-- 
Franco Martelli
Re: Bash: check if a value is into an array
#259
Author: Greg Wooledge
Date: Thu, 22 Oct 2026 17:10
41 lines
3634 bytes
On Thu, Oct 22, 2026 at 22:45:21 +0700, Max Nikulin wrote:
> On 22/10/2026 1:48 am, Nicolas George wrote:
> > By the way, it seems what you want is not just distinct elements but all
> > the elements too: a permutation. For that, there is a much more
> > efficient algorithm: swap the first element randomly with any of the
> > elements, then the second with any of the elements except the first,
> > etc.
> 
> shuf(1) or, as it is recommended there,
> (info "(coreutils) shuf invocation")
> Unless the real goal is to explore BASH arrays.

Harnessing shuf(1) to shuffle a list of filenames presents its own flavor
of challenge.  It's not trivial, because of the nature of filenames.
It's not exactly *hard*, but you do have to know what you're doing.
(shuf(1) is also non-portable, but since this is a Debian list, I guess
we can assume it will be available.)

If you don't want to puzzle it out yourself, here's a shuf-based
example.  This one requires bash 4.4 or higher (for readarray -d):

#!/bin/bash

cd /wherever || exit
readarray -t -d '' playlist < <( printf '%s\0' * | shuf -z )
for file in "${playlist[@]}"; do
    mpv -- "$file"
done

If you're targeting older versions of bash, you'd need a while loop to
load the array.

"But Greg," I hear you say, "why are you messing around with NUL bytes?
Why not just use newlines?"

Filenames may contain newlines.  NUL is the only safe delimiter for
filenames.  Any tool that processes filenames as input or output, or
which may be *expected* to be used in that way, needs to have a -z or -0
or --null option.  And your bash script needs to use that option, and
perform all the other steps necessary to accomodate hostile filenames,
or else it *will* break.
Re: Bash: check if a value is into an array
#262
Author: Franco Martelli
Date: Thu, 22 Oct 2026 17:40
19 lines
4679 bytes
On 22/10/26 at 18:54, Charles Curley wrote:
> Another way to get your playlist played randomly and non-repeatably is
> to use vlc and have it play randomly within the playlist. I suspect
> other players can do similarly.

I've already tried vlc, maybe for songs it's fine but for video clips 
it's a pain, it continuously adapt the window at the file resolution 
enlarging and shrinking file after file played.

I did many attempts to set a fixed resolution but all failed, so I 
decided to write a shell script and to use "ffplay".
"ffplay" works fine, the window appear centered on the screen and right 
clicking with the mouse on the left or on the right side of the window 
it moves the timeline (seek) respectively at the begin or at the end of 
the video.

Kind regards,
-- 
Franco Martelli
Re: Bash: check if a value is into an array
#263
Author: Jeffrey Walton
Date: Thu, 22 Oct 2026 17:40
50 lines
5539 bytes
On Wed, Oct 21, 2026 at 12:34 PM Franco Martelli <martellif67@gmail.com> wrote:
>
> Hi,
>
> I run into issue trying to populate an array with unique random value,
> the issue is that I have an endless loop, here the snippet:
>
> ...
> # Populate playlist array with unique random values
> while [ "$index" -le "$total" ]; do
>          clip="$(/usr/bin/numrandom /1..$total/)"
>          if [[ ! ${playlist[@]} =~ "$clip" ]]; then      # [ -z
> ${rndarr[clip]} ]; then
>                                                          # rndarr[$clip]=1
>                 playlist[$index]=$clip
>                 ((index++))
>          fi
> done
> ...

The code is broken:

$ shellcheck test.sh

In test.sh line 2:
while [ "$index" -le "$total" ]; do
^-- SC1009 (info): The mentioned syntax error was in this while loop.

In test.sh line 4:
        if [[ ! ${playlist[@]} =~ "$clip" ]]; then      # [ -z
        ^-- SC1046 (error): Couldn't find 'fi' for this 'if'.
        ^-- SC1073 (error): Couldn't parse this if expression. Fix to allow mor
e checks.


In test.sh line 5:
${rndarr[clip]} ]; then
                  ^-- SC1047 (error): Expected 'fi' matching previously mention
ed 'if'.
                      ^-- SC1072 (error): Unexpected keyword/token. Fix any men
tioned problems and try again.

Perhaps you can supply a working example?

Jeff
Re: Bash: check if a value is into an array
#264
Author: Greg Wooledge
Date: Thu, 22 Oct 2026 17:50
18 lines
2455 bytes
On Thu, Oct 22, 2026 at 13:37:52 -0400, Jeffrey Walton wrote:
> On Wed, Oct 21, 2026 at 12:34 PM Franco Martelli <martellif67@gmail.com> wrote:
> > # Populate playlist array with unique random values
> > while [ "$index" -le "$total" ]; do
> >          clip="$(/usr/bin/numrandom /1..$total/)"
> >          if [[ ! ${playlist[@]} =~ "$clip" ]]; then      # [ -z
> > ${rndarr[clip]} ]; then
> >                                                          # rndarr[$clip]=1
> >                 playlist[$index]=$clip
> >                 ((index++))
> >          fi
> > done
> > ...
> 
> The code is broken:

You need to account for line wrapping.  The "line" beginning with
${rndarr[clip]} is supposed to be attached to the # [ -z above it.
Re: Bash: check if a value is into an array
#265
Author: Franco Martelli
Date: Thu, 22 Oct 2026 18:20
54 lines
5253 bytes
On 22/10/26 at 19:37, Jeffrey Walton wrote:
> On Wed, Oct 21, 2026 at 12:34 PM Franco Martelli <martellif67@gmail.com> wrote:
>>
>> Hi,
>>
>> I run into issue trying to populate an array with unique random value,
>> the issue is that I have an endless loop, here the snippet:
>>
>> ...
>> # Populate playlist array with unique random values
>> while [ "$index" -le "$total" ]; do
>>           clip="$(/usr/bin/numrandom /1..$total/)"
>>           if [[ ! ${playlist[@]} =~ "$clip" ]]; then      # [ -z
>> ${rndarr[clip]} ]; then
>>                                                           # rndarr[$clip]=1
>>                  playlist[$index]=$clip
>>                  ((index++))
>>           fi
>> done
>> ...
> 
> The code is broken:
> 
> $ shellcheck test.sh
> 
> In test.sh line 2:
> while [ "$index" -le "$total" ]; do
> ^-- SC1009 (info): The mentioned syntax error was in this while loop.
> 
> In test.sh line 4:
>          if [[ ! ${playlist[@]} =~ "$clip" ]]; then      # [ -z
>          ^-- SC1046 (error): Couldn't find 'fi' for this 'if'.
>          ^-- SC1073 (error): Couldn't parse this if expression. Fix to allow mor
> e checks.
> 
> 
> In test.sh line 5:
> ${rndarr[clip]} ]; then
>                    ^-- SC1047 (error): Expected 'fi' matching previously mention
> ed 'if'.
>                        ^-- SC1072 (error): Unexpected keyword/token. Fix any men
> tioned problems and try again.
> 
> Perhaps you can supply a working example?

already clarified, maybe a matching issue in the "if [[ ! ${playlist[@]} 
=~ "$clip" ]]; then" statement, please see "Second note:" in the 
following email:

https://lists.debian.org/debian-user/2026/10/msg00376.html

Kind regards,
-- 
Franco Martelli
Re: Bash: check if a value is into an array
#268
Author: Max Nikulin
Date: Fri, 23 Oct 2026 02:50
15 lines
3739 bytes
On 23/10/2026 12:08 am, Greg Wooledge wrote:
> Harnessing shuf(1) to shuffle a list of filenames presents its own flavor
> of challenge.
[...]
> cd /wherever || exit
> readarray -t -d '' playlist < <( printf '%s\0' * | shuf -z )
> for file in "${playlist[@]}"; do
>      mpv -- "$file"
> done

I had in mind something like

find /wherever -type f -print0 | shuf -z -n 10 | xargs -0 -n 1 mpv --

perhaps with more filtering options.
Re: Bash: check if a value is into an array
#269
Author: Michel Verdier
Date: Fri, 23 Oct 2026 06:40
13 lines
2170 bytes
On 2026-10-22, tomas@tuxteam.de wrote:

> Greg,
>
> as someone who writes occasionaly shell, and has been doing
> that for longer he'd like to admit, I want to thank your for
> your posts: always informative, precise, and a pleasure to
> read.
>
> There, had to be said.

And it had to be confirmed :)
Thanks Greg
Re: Bash: check if a value is into an array
#276
Author: Anssi Saari
Date: Fri, 23 Oct 2026 14:20
12 lines
2500 bytes
The Wanderer <wanderer@fastmail.fm> writes:

> $ 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'.

The coolest thing about this brace expansion is that you can even get
the numbers zero padded for a fixed width, like maybe for filenames or
tabular data.

So echo {01..10} outputs 01 02 03 04 05 06 07 08 09 10.
Re: Bash: check if a value is into an array
#278
Author: Franco Martelli
Date: Fri, 23 Oct 2026 15:30
77 lines
6173 bytes
On 22/10/26 at 16:22, Greg Wooledge wrote:
> For this project, it would be better to shuffle the array of files
> instead of selecting one at a time.
> 
> #!/bin/bash
> 
> # Gather the files.
> cd ~/Video/clips/partyzone/ || exit
> playlist=([0-9][0-9][0-9][0-9]*)
> 
> # Shuffle the playlist.
> n=${#playlist[@]}
> for ((i=n-1; i>0; i--)); do
>      max=$(( 32768 / (i+1) * (i+1) ))
>      while (( (rand=RANDOM) >= max )); do :; done
>      rand=$(( rand % (i+1) ))
>      tmp=${playlist[i]} playlist[i]=${playlist[rand]} playlist[rand]=$tmp
> done
> 
> # Play the shuffled playlist.
> for clip in "${playlist[@]}"; do
>      ffplay -vf "scale=720:576,setdar=720/576" -autoexit -volume 10 \
>          "$clip" >/dev/null 2>&1
> done
> 
> You can add your trap if you want it.

Greg, there is something odd in the random number generator, when you 
have some spare time could you take a look at the code, please:

...
#!/bin/bash

# Gather the files.
cd ~/Video/clips/partyzone/ || exit
playlist=([0-9][0-9][0-9][0-9]*)
declare -a assigned	# Declare an indexed array of name: assigned
# set -x
# Shuffle the playlist.
n=${#playlist[@]}
for ((i=n; i>0; )); do
	max=$(( 32768 / (i+1) * (i+1) ))
	while (( (rand=RANDOM) >= max )); do :; done
	rand=$(( rand % (i+1) ))
	rand=$((RANDOM % n))
	if [ -z "${assigned[rand]}" ]; then
		assigned[$rand]=1
		((i--))
	else
		continue
	fi
	tmp=${playlist[i]} playlist[i]=${playlist[rand]} playlist[rand]=$tmp
	echo $rand
done
exit

# Play the shuffled playlist.
for clip in "${playlist[@]}"; do
	ffplay -vf "scale=720:576,setdar=720/576" -autoexit -volume 10 "$clip" 
 >/dev/null 2>&1
done

I've added the "if [ -z "${assigned[rand]}" ]; then" statement because 
$rand had many occurrences of the same value so I tried with the 
"assigned[$rand]" array to avoid that, looping in the circumstance 
"$rand" had a value already assigned.

The issue is that when I comment out the line "rand=$((RANDOM % n))" and 
place ((i=n-1; i>0; )) in the "for" statement header, the script runs in 
an endless loop. :(
I don't know why, I tried to enable debug with "set -x" but for me 
doesn't help, it looks like that the range of generated value is too 
small to complete "i--" iterations, maybe I'm wrong.

Thanks in advance, kind regards,
-- 
Franco Martelli
Bash: brace expansion [was: Bash: check if a value is into an array]
#279
Author: tomas
Date: Fri, 23 Oct 2026 15:30
58 lines
3413 bytes
--m5eLFotwSlRBJn1Q
Content-Type: text/plain; charset=utf-8
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Fri, Oct 23, 2026 at 05:18:37PM +0300, Anssi Saari wrote:
> The Wanderer <wanderer@fastmail.fm> writes:
>=20
> > $ 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'.
>=20
> The coolest thing about this brace expansion is that you can even get
> the numbers zero padded for a fixed width, like maybe for filenames or
> tabular data.
>=20
> So echo {01..10} outputs 01 02 03 04 05 06 07 08 09 10.

And it does letters:

    echo {a..l}
    =3D> a b c d e f g h i j k l

=2E..and it composes...

    echo xy{1..3}zzy
    =3D> xy1zzy xy2zzy xy3zzy

=2E..in a Cartesian way...

    echo {1..3}{x..z}
    =3D> 1x 1y 1z 2x 2y 2z 3x 3y 3z

    echo {1..3}{x..z}{2..3}
    =3D> 1x2 1x3 1y2 1y3 1z2 1z3 2x2 2x3 2y2 2y3 2z2 2z3 3x2 3x3 3y2 3y3 3z=
2 3z3

(I get reminiscences of APL)

(OK, OK, I'm stopping now ;-)

Enjoy
--=20
t

--m5eLFotwSlRBJn1Q
Content-Type: application/pgp-signature; name="signature.asc"

-----BEGIN PGP SIGNATURE-----

iF0EABECAB0WIQRp53liolZD6iXhAoIFyCz1etHaRgUCatt7HAAKCRAFyCz1etHa
RhyoAJ0XHYBrzFja0mceo4bHFxYG0U0h2gCfd1uKIVOPNxyi+zx7ZTJ2TlW2gHc=
=OEc3
-----END PGP SIGNATURE-----

--m5eLFotwSlRBJn1Q--
Re: Bash: check if a value is into an array
#280
Author: Greg Wooledge
Date: Fri, 23 Oct 2026 15:40
89 lines
5141 bytes
On Fri, Oct 23, 2026 at 17:26:02 +0200, Franco Martelli wrote:
> On 22/10/26 at 16:22, Greg Wooledge wrote:
> > # Shuffle the playlist.
> > n=${#playlist[@]}
> > for ((i=n-1; i>0; i--)); do
> >      max=$(( 32768 / (i+1) * (i+1) ))
> >      while (( (rand=RANDOM) >= max )); do :; done
> >      rand=$(( rand % (i+1) ))
> >      tmp=${playlist[i]} playlist[i]=${playlist[rand]} playlist[rand]=$tmp
> > done

That's how the shuffle loop is supposed to be.

> Greg, there is something odd in the random number generator, when you have
> some spare time could you take a look at the code, please:
> 
> ...
> #!/bin/bash
> 
> # Gather the files.
> cd ~/Video/clips/partyzone/ || exit
> playlist=([0-9][0-9][0-9][0-9]*)
> declare -a assigned	# Declare an indexed array of name: assigned
> # set -x
> # Shuffle the playlist.
> n=${#playlist[@]}
> for ((i=n; i>0; )); do
> 	max=$(( 32768 / (i+1) * (i+1) ))
> 	while (( (rand=RANDOM) >= max )); do :; done
> 	rand=$(( rand % (i+1) ))
> 	rand=$((RANDOM % n))

Here, you've undone all the work from the previous 3 lines, and
overwritten rand, using a selection from an incorrect range.

This is simply wrong.  Don't add this line.

> 	if [ -z "${assigned[rand]}" ]; then
> 		assigned[$rand]=1
> 		((i--))
> 	else
> 		continue
> 	fi

What are you even trying to do here?  This makes no sense.  The
loop as I wrote it is shuffling the whole array.  When it's done,
the array *is* the playlist.

Your addition is building up a second array for no reason, and
messing with the loop counter's value.

Don't add this either.

> 	tmp=${playlist[i]} playlist[i]=${playlist[rand]} playlist[rand]=$tmp
> 	echo $rand
> done
> exit
> 
> # Play the shuffled playlist.
> for clip in "${playlist[@]}"; do
> 	ffplay -vf "scale=720:576,setdar=720/576" -autoexit -volume 10 "$clip"
> >/dev/null 2>&1
> done

> I've added the "if [ -z "${assigned[rand]}" ]; then" statement because $rand
> had many occurrences of the same value so I tried with the "assigned[$rand]"
> array to avoid that, looping in the circumstance "$rand" had a value already
> assigned.

It's *fine* if rand gets the same value more than once in this loop.
It just means that particular slot in the playlist will be swapped
more than once.  It doesn't mean a song will be repeated.

I suspect you don't understand what the original code is doing.  I added
the comments for a reason -- they tell you what each section does.
I didn't explain every line, because that's not how code comments should
be used.

If you need help understanding the original code (e.g. an explanation
of every single line, one by one), feel free to ask.

Are you stuck on the word "shuffle"?  It's normally used with a deck of
playing cards.  If you have a deck of cards, and you shuffle it, then
the same cards are still in the deck, but they're in a different, random,
order.  You don't magically get two of the same card, unless your deck
started out with duplicates.

That's what this loop is doing.  It takes your array of filenames and
shuffles it.  The filenames are randomly re-ordered.
Re: Bash: check if a value is into an array
#283
Author: Franco Martelli
Date: Fri, 23 Oct 2026 18:20
47 lines
5910 bytes
On 23/10/26 at 17:36, Greg Wooledge wrote:
>> I've added the "if [ -z "${assigned[rand]}" ]; then" statement because $rand
>> had many occurrences of the same value so I tried with the "assigned[$rand]"
>> array to avoid that, looping in the circumstance "$rand" had a value already
>> assigned.

> It's*fine* if rand gets the same value more than once in this loop.
> It just means that particular slot in the playlist will be swapped
> more than once.  It doesn't mean a song will be repeated.

In my understanding I supposed that some clip was left in its original 
position (skipped) but now I realize that it is not possible because 
"$i" changes for each iteration.

> 
> I suspect you don't understand what the original code is doing.  I added
> the comments for a reason -- they tell you what each section does.
> I didn't explain every line, because that's not how code comments should
> be used.

I had my coding in my mind. That it encompassed an unique $rand value 
necessary as array index to shuffle the playlist[], as I did in my 
previous coding. In other words I did a sort of confusion mixing my 
previously coding concepts and apply them to your code.

> 
> If you need help understanding the original code (e.g. an explanation
> of every single line, one by one), feel free to ask.
> 
> Are you stuck on the word "shuffle"?  It's normally used with a deck of
> playing cards.  If you have a deck of cards, and you shuffle it, then
> the same cards are still in the deck, but they're in a different, random,
> order.  You don't magically get two of the same card, unless your deck
> started out with duplicates.

No, I'm OK with the "shuffle" meaning.

> 
> That's what this loop is doing.  It takes your array of filenames and
> shuffles it.  The filenames are randomly re-ordered.

I apologize for the noise, but since I was unsure, I decided to write 
you an email, I'll restore the code to its original state.

Kind regards,
-- 
Franco Martelli
Re: Bash: brace expansion [was: Bash: check if a value is into an array]
#305
Author: Franco Martelli
Date: Mon, 26 Oct 2026 16:10
56 lines
5150 bytes
On 23/10/26 at 17:20, tomas@tuxteam.de wrote:
> On Fri, Oct 23, 2026 at 05:18:37PM +0300, Anssi Saari wrote:
>> The Wanderer <wanderer@fastmail.fm> writes:
>>
>>> $ 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'.
>>
>> The coolest thing about this brace expansion is that you can even get
>> the numbers zero padded for a fixed width, like maybe for filenames or
>> tabular data.
>>
>> So echo {01..10} outputs 01 02 03 04 05 06 07 08 09 10.
> 
> And it does letters:
> 
>      echo {a..l}
>      => a b c d e f g h i j k l
> 
> ...and it composes...
> 
>      echo xy{1..3}zzy
>      => xy1zzy xy2zzy xy3zzy
> 
> ...in a Cartesian way...
> 
>      echo {1..3}{x..z}
>      => 1x 1y 1z 2x 2y 2z 3x 3y 3z
> 
>      echo {1..3}{x..z}{2..3}
>      => 1x2 1x3 1y2 1y3 1z2 1z3 2x2 2x3 2y2 2y3 2z2 2z3 3x2 3x3 3y2 3y3 3z2 3z3
> 
> (I get reminiscences of APL)
> 
> (OK, OK, I'm stopping now ;-)
> 
> Enjoy

Why splitting in multiple lines a sequence doesn't work:

~$ IFS=$'\n' echo {001..136}

I would expect:

001
002
003
...

instead I got the sequence expanded on a single line, have I to use "tr" 
forcibly?

Kind regards,
-- 
Franco Martelli
Re: Bash: brace expansion [was: Bash: check if a value is into an array]
#307
Author: Greg Wooledge
Date: Mon, 26 Oct 2026 17:20
47 lines
4048 bytes
On Mon, Oct 26, 2026 at 17:06:29 +0100, Franco Martelli wrote:
> Why splitting in multiple lines a sequence doesn't work:
> 
> ~$ IFS=$'\n' echo {001..136}
> 
> I would expect:
> 
> 001
> 002
> 003
> ...

You've got a few conceptual mistakes here.  First of all, IFS is not
used by the echo command at all.  Setting IFS simply has no effect on
what echo does.

The echo command always separates its arguments with a single space
character.  This is true whether it's the builtin shell echo, or the
external /bin/echo command.  And since it's the same either way, you
can conclude that IFS would have no effect, since no external command
sees it or respects it.

IFS is used by the read command, and it's used by the shell when it
does Word Splitting, or "$*" type expansions.  But there is no Word
Splitting happening here.  Even if there were some, the way you're
setting IFS (putting it into the temporary environment of the echo
command) would not cause the words to be split the way you want.
Cf. <https://mywiki.wooledge.org/BashFAQ/104>

Brace expansion produces a list of words, and since your words have
no characters in them that would cause further rounds of expansions,
that list is passed directly to echo as an argument vector.  You're
running the command

    echo 001 002 003 ...

and therefore echo writes the first argument, a space, the second
argument, a space, and so on until the final argument, after which it
writes a newline.

Finally, I wonder what you intend to *do* with the output of echo here.
Why do you want a stream of zero-padded three-digit numbers separated
by newlines?

Whatever you're going to do with this stream of characters, there's
probably some easier or more efficient way to do it.  But we need to
know what the goal is, so we can advise you.
Re: Bash: brace expansion [was: Bash: check if a value is into an array]
#308
Author: Franco Martelli
Date: Mon, 26 Oct 2026 18:30
23 lines
4885 bytes
On 26/10/26 at 18:15, Greg Wooledge wrote:
> Finally, I wonder what you intend to*do* with the output of echo here.
> Why do you want a stream of zero-padded three-digit numbers separated
> by newlines?
> 
> Whatever you're going to do with this stream of characters, there's
> probably some easier or more efficient way to do it.  But we need to
> know what the goal is, so we can advise you.

As usual thanks Greg for the clarifications. I'm still playing with the 
RNG code of the script that shuffle a playlist, since it depends on a 
list of filenames in a given directory, I'd like now that the indexed 
array "playlist" be populated by a sequence of numbers instead of 
filenames, this works:

playlist=({001..136})

but the whole sequence is expanded on a single line. I'd like that each 
number be separated by newline \n.

Kind regards,
-- 
Franco Martelli
Re: Bash: brace expansion [was: Bash: check if a value is into an array]
#309
Author: Greg Wooledge
Date: Mon, 26 Oct 2026 18:40
54 lines
3838 bytes
On Mon, Oct 26, 2026 at 19:21:48 +0100, Franco Martelli wrote:
> As usual thanks Greg for the clarifications. I'm still playing with the RNG
> code of the script that shuffle a playlist, since it depends on a list of
> filenames in a given directory, I'd like now that the indexed array
> "playlist" be populated by a sequence of numbers instead of filenames, this
> works:
> 
> playlist=({001..136})

I don't understand the need for this array, but hold that thought.

> but the whole sequence is expanded on a single line. I'd like that each
> number be separated by newline \n.

printf '%d\n' "${playlist[@]}"

I still don't know why you want that output, though.

Now, back to the original thought.  If you've got a playlist array
that contains filenames, then that array is *already* numerically
indexed.

playlist=(clip1 clip2 clip3 clip4)
for i in "${!playlist[@]}"; do
    printf 'Index %d is "%s"\n' "$i" "${playlist[i]}"
done

Running this code gives us:

Index 0 is "clip1"
Index 1 is "clip2"
Index 2 is "clip3"
Index 3 is "clip4"

So, from what I can see, you only want to make two changes:

  1) Count starting from 1 instead of 0.
  2) Zero-pad each index to 3 digits.

printf plus the shell's builtin arithmetic allows us to do this easily:

playlist=(clip1 clip2 clip3 clip4)
for i in "${!playlist[@]}"; do
    printf 'Index %03d is "%s"\n' "$((i+1))" "${playlist[i]}"
done

That gives us:

Index 001 is "clip1"
Index 002 is "clip2"
Index 003 is "clip3"
Index 004 is "clip4"

Is that all you needed?
Re: Bash: brace expansion [was: Bash: check if a value is into an array]
#310
Author: Greg Wooledge
Date: Mon, 26 Oct 2026 22:30
68 lines
4236 bytes
On Mon, Oct 26, 2026 at 20:59:39 +0100, john doe wrote:
> On 10/26/26 8:20 PM, Franco Martelli wrote:
> > On 26/10/26 at 19:38, Greg Wooledge wrote:
> > > On Mon, Oct 26, 2026 at 19:21:48 +0100, Franco Martelli wrote:
> > > > As usual thanks Greg for the clarifications. I'm still playing
> > > > with
> > not output, as input to populate the array, John Doe suggested:
> > 
> > playlist=($(printf "%d\n" {001..136}))
> > 
> "playlist=($(printf "%s\n" {001..136}))" looks to be a tad better!

They're both insane.  Neither one makes any sense!

An array *does not contain a newline-delimited string of data*.  It
contains string elements, and each string element is pointed to by
a non-negative integer index.

Consider these arrays:

    a=( 1 2 3 4 )
    b=( $(echo "1 2 3 4") )
    c=( $(printf '%s\n' {1..4}) )

What are the differences among them?

It's a trick question!  There are no differences!  After running those
lines of code, we have:

hobbit:~$ declare -p a b c 
declare -a a=([0]="1" [1]="2" [2]="3" [3]="4")
declare -a b=([0]="1" [1]="2" [2]="3" [3]="4")
declare -a c=([0]="1" [1]="2" [2]="3" [3]="4")

They're identical.

If you're populating an array using Word Splitting applies to a Command
Substitution (which is what b and c are using), it doesn't *matter*
whether the string elements are separated by spaces, tabs, or newlines.
Word Splitting treats them all the same.

Look at the assignment of c in detail.  We have an inner command (inside
the Command Substitution) of

    printf '%s\n' {1..4}

This generates the following string of characters:

1
2
3
4

When Word Splitting is done on this string, the results are the words
1, 2, 3, and 4.  So, those become the array's elements.  It's exactly
the same as if you had done:

    c=(
    1
    2
    3
    4
    )

(Yes, that is valid syntax.)  You get the same array in the end.

So my question remains: *why* do you want a newline-delimited string
of numbers?
Re: Bash: brace expansion [was: Bash: check if a value is into an array]
#311
Author: Greg Wooledge
Date: Tue, 27 Oct 2026 12:10
80 lines
5078 bytes
On Tue, Oct 27, 2026 at 07:38:01 +0100, john doe wrote:
> Now that  I have publicly humiliated myself, lets make it a learning
> moment!!! ;^)
> 
> What would be the correct way to populate an array programmatically?

Depends on what you're putting in it.  If it's just a fixed set of
strings, simply write them out:

    a=( zero one two three )
    b=( {0..9} )
    c=(
        "The first element is a sentence."
        "So is the second element."
        "I'm not."              # ???
        "Yes, you are!"
    )
    # Yes, you can put comments inside this format.

If it's filenames, use a glob (pathname expansion):

    d=( ~/wallpaper/* )

Remember that the glob characters, and in this case the tilde, are
supposed to be expanded by the shell, so they must not be quoted.  If
there's a separate part of the word that needs to be quoted, then
put the quotes only around that part:

    e=( "$cfgdir"/*.conf )

If the array is populated by the output of a program, then use the
readarray (a.k.a. mapfile) builtin, or a loop:

    readarray -t f < <(something that writes one element per line)

    readarray -d '' -t g < <(something that writes NUL-delimited elements)

    # This is what we used before readarray -d ''
    h=()
    while LC_ALL=C IFS= read -r -d '' file; do
        h+=( "$file" )
    done < <(find ... -print0)

*Do not* use this with a naive ls command.

    # Don't do this!
    readarray -t wrong < <(ls *.gif)

ls will often mangle filenames, and even if it doesn't, filenames that
contain newlines will break this.  If you want to load the filenames
from a directory non-recursively, use the glob syntax:

    i=( *.gif )

If you need to grab them recursively, use find with -print0:

    readarray -d '' -t j < <(find . -type f -name '*.gif' -print0)

Or you can use bash's globstar option:

    shopt -s globstar
    k=( **/*.gif )

If you need to get the filenames in an order that isn't what globbing
produces (e.g. sorted by mtime), GNU coreutils ls has special options
that can make this work.  I cover this at
<https://mywiki.wooledge.org/ParsingLs#Notes_on_GNU_coreutils_ls> and
I'll show the first example here:

    # Delete the 5 oldest files
    # in the current directory.
    readarray -t -d '' -n 5 sorted < <(ls --zero -tr)
    (( ${#sorted[@]} == 0 )) || rm -- "${sorted[@]}"

If your ls command doesn't have a --zero option, or a --quoting-style
option, then you can't use it to grab filenames programmatically.
GNU find with a fancy -printf option would be your next recourse.
There's an example on <https://mywiki.wooledge.org/BashProgramming/03>
(search for rlart) but it doesn't use arrays, and it's a bit beyond the
complexity limit for this email.
Thread Navigation

This is a paginated view of messages in the thread with full content displayed inline.

Messages are displayed in chronological order, with the original post highlighted in green.

Use pagination controls to navigate through all messages in large threads.

Back to All Threads