🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: linux.debian.user
Article #235

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

#235
From: 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.
Technical Details
Message-ID: <NQJRf-729Y-1@gated-at.bofh.it>
Path: mbox-mo1.pugleaf.net!archive.usenet.blueworldhosting.com!usenet.blueworldhosting.com!diablo1.usenet.blueworldhosting.com!news.samoylyk.net!gothmog.csi.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>

Show Full Headers
Complete Article Headers
Path: mbox-mo1.pugleaf.net!archive.usenet.blueworldhosting.com!usenet.blueworldhosting.com!diablo1.usenet.blueworldhosting.com!news.samoylyk.net!gothmog.csi.it!bofh.it!news.nic.it!robomod
From: Greg Wooledge <greg@wooledge.org>
Newsgroups: linux.debian.user
Subject: Re: Bash: check if a value is into an array
Date: Wed, 21 Oct 2026 21:10:01 +0200
Message-ID: <NQJRf-729Y-1@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>
X-Original-To: Franco Martelli <martellif67@gmail.com>
X-Mailbox-Line: From debian-user-request@lists.debian.org  Wed Oct 21 19:04:44 2026
Old-Return-Path: <greg@wooledge.org>
X-Amavis-Spam-Status: No, score=-1.9 tagged_above=-10000 required=5.3
 tests=[BAYES_00=-1.9] autolearn=ham autolearn_force=no
X-Policyd-Weight: using cached result; rate: -4.6
Mail-Followup-To: Franco Martelli <martellif67@gmail.com>,
	debian-user@lists.debian.org
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
User-Agent: Mutt/1.10.1 (2018-07-13)
X-Mailing-List: <debian-user@lists.debian.org> archive/latest/832541
List-ID: <debian-user.lists.debian.org>
List-URL: <https://lists.debian.org/debian-user/>
List-Archive: https://lists.debian.org/msgid-search/20261021190429.GA28455@wooledge.org
Approved: robomod@news.nic.it
Lines: 69
Organization: linux.* mail to news gateway
Sender: robomod@news.nic.it
X-Original-Cc: debian-user@lists.debian.org
X-Original-Date: Wed, 21 Oct 2026 15:04:29 -0400
X-Original-Message-ID: <20261021190429.GA28455@wooledge.org>
X-Original-References: <fb4588c5-2637-4714-81e6-791a9260afbd@gmail.com>
 <20261021150743.GA21484@wooledge.org>
 <b397ac30-dbff-4822-b314-c6cc97dc0df8@gmail.com>