🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: linux.debian.user
Article #250

Re: Bash: check if a value is into an array

#250
From: 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
Technical Details
Message-ID: <NR1br-7bQc-11@gated-at.bofh.it>
Path: mbox-mo1.pugleaf.net!archive.usenet.blueworldhosting.com!usenet.blueworldhosting.com!diablo1.usenet.blueworldhosting.com!3.eu.feeder.erje.net!feeder.erje.net!fu-berlin.de!news.servidellagleba.it!bofh.it!news.nic.it!robomod
References: <NQFND-6ZMU-9@gated-at.bofh.it> <NQG6Z-703J-7@gated-at.bofh.it> <NQJod-71PP-13@gated-at.bofh.it> <NQJRf-729Y-1@gated-at.bofh.it>

Show Full Headers
Complete Article Headers
Path: mbox-mo1.pugleaf.net!archive.usenet.blueworldhosting.com!usenet.blueworldhosting.com!diablo1.usenet.blueworldhosting.com!3.eu.feeder.erje.net!feeder.erje.net!fu-berlin.de!news.servidellagleba.it!bofh.it!news.nic.it!robomod
From: Franco Martelli <martellif67@gmail.com>
Newsgroups: linux.debian.user
Subject: Re: Bash: check if a value is into an array
Date: Thu, 22 Oct 2026 15:40:01 +0200
Message-ID: <NR1br-7bQc-11@gated-at.bofh.it>
References: <NQFND-6ZMU-9@gated-at.bofh.it> <NQG6Z-703J-7@gated-at.bofh.it> <NQJod-71PP-13@gated-at.bofh.it> <NQJRf-729Y-1@gated-at.bofh.it>
X-Original-To: Greg Wooledge <greg@wooledge.org>
X-Mailbox-Line: From debian-user-request@lists.debian.org  Thu Oct 22 13:37:25 2026
Old-Return-Path: <martellif67@gmail.com>
X-Amavis-Spam-Status: No, score=-1.849 tagged_above=-10000 required=5.3
 tests=[BAYES_00=-1.9, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1,
 DKIM_VALID_EF=-0.1, FREEMAIL_ENVFROM_END_DIGIT=0.25, FREEMAIL_FROM=0.001,
 RCVD_IN_DNSWL_NONE=-0.0001] autolearn=ham autolearn_force=no
X-Policyd-Weight: NOT_IN_SBL_XBL_SPAMHAUS=-1.5 CL_IP_EQ_HELO_IP=-2 (check from: .gmail. - helo: .mail-wm1-x336.google. - helo-domain: .google.)  FROM/MX_MATCHES_HELO(DOMAIN)=-2; rate: -5.5
X-Gm-Message-State: AFq9FYIgCya0CLRhxOyucomCUReAlJUev3VsESbn8ZJm1oTVKDmNjEKu
	neiz70OjMC4hO2xJHxKa6GB2XGQb9NoA8mUbwd9+QypCPH60acAYRvE6Wl976A==
X-Gm-Gg: AYBFou1JLIZoQ1tBspOsoRlnm1g08kCyEEp4EO8iwC4lDtt5YcZlsIxvF1VGf4YUIng
	JhihnYhy1N6abUmIhlaY4aSDxPRMM6rZsNTYYgBEXWemk2b5r1csj3+KKielf0IZxIPS/RJu4Ll
	1SoriN838s/tSi/LLf8h70WUwdQUcFuJdZB+L7a6CrzEvlHJkpDNJ/CYsN2JtrhXazuWVPtcLXg
	CaVKLP+sBXx0O4ggbdHTvxp+n4URMWhbhCe8UoS8QIurTQaarxkl/uGnurWrgT7Fxp3gu1EmrzI
	ATy0WfAWaWUGvJA0m+oC8VD2hfyKsN0CdFiVBIiJrEO98tRPm3NddYMEVEdnzCSeRUXDdmYwzwr
	gAsL5fT6VLxVrpamohuCo+ZEf3Cj4eVu2SkFb28k255MrYEuLXlo8vYO5++FXrbR8EN3zh/csey
	qA8fYEYT4q7sDy/OZYZ/6V7U4+tRXi+nCxcKINetsyLoGEhQBU9/lWrVfMN17DqzFFMsN+O1hip
	4xtElALMXAafgRJwJMGY9pAr8eYcZLlTNYtLLCLM8oTtRhVYugVvuceOAcLjRwodkcse3aWquoC
	EHKtw896g0Di
X-Received: by 2002:a05:600c:a411:b0:4a2:40:8d2c with SMTP id 5b1f17b1804b1-4a200408d40mr69571455e9.26.1792676231447;
        Thu, 22 Oct 2026 06:37:11 -0700 (PDT)
MIME-Version: 1.0
User-Agent: Mozilla Thunderbird
Content-Language: en-US
Autocrypt: addr=martellif67@gmail.com; keydata=
 xjMEXwx9ehYJKwYBBAHaRw8BAQdA8CkGKYFI/MK9U3RPhzE5H/ul7B6bHu/4BIhTf6LLO47N
 J0ZyYW5jbyBNYXJ0ZWxsaSA8bWFydGVsbGlmNjdAZ21haWwuY29tPsKWBBMWCAA+FiEET9sW
 9yyU4uM6QbloXEn0O0LcklAFAmhyroACGwMFCQ0ncuYFCwkIBwIGFQoJCAsCBBYCAwECHgEC
 F4AACgkQXEn0O0LcklAHVwD9H5JZ52g292FD8w0x6meDD8y/6KkNpzuaLHP6/Oo8kAIBAJsh
 aMB9LdCBJTMtnxU8JTHtAoGOZ/59UJWeZIkuWJUNzjgEXwx9ehIKKwYBBAGXVQEFAQEHQNP5
 V2q0H0oiJu89h1SSPgQDtkixXvUvRf1rNLLIcNpPAwEIB8J+BBgWCAAmFiEET9sW9yyU4uM6
 QbloXEn0O0LcklAFAmhyroACGwwFCQ0ncuYACgkQXEn0O0LcklASVwEAoEkHMEU7mHc0zmAu
 D2R1PYsDh9+3wQeied5PrF+HdakBAOeSGsf40GBew5umZuM59I04d1uXYAXGMP+jGN2RUtMA
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
X-Mailing-List: <debian-user@lists.debian.org> archive/latest/832558
List-ID: <debian-user.lists.debian.org>
List-URL: <https://lists.debian.org/debian-user/>
List-Archive: https://lists.debian.org/msgid-search/02f8c2b4-80ec-4f0a-a277-3f1c80acd476@gmail.com
Approved: robomod@news.nic.it
Lines: 127
Organization: linux.* mail to news gateway
Sender: robomod@news.nic.it
X-Original-Cc: debian-user@lists.debian.org
X-Original-Date: Thu, 22 Oct 2026 15:37:09 +0200
X-Original-Message-ID: <02f8c2b4-80ec-4f0a-a277-3f1c80acd476@gmail.com>
X-Original-References: <fb4588c5-2637-4714-81e6-791a9260afbd@gmail.com>
 <20261021150743.GA21484@wooledge.org>
 <b397ac30-dbff-4822-b314-c6cc97dc0df8@gmail.com>
 <20261021190429.GA28455@wooledge.org>