0

I want to generate a random number from given list

For example if I give the numbers

1,22,33,400,400,23,12,53 etc.

I want to select a random number from the given numbers.

1
  • 2
    Put them in an array, rand mod the size of the array. Commented Sep 21, 2016 at 14:30

1 Answer 1

1

Couldn't find an exact duplicate of this. So here goes my attempt, exactly what 123 mentions in comments. The solution is portable across shell variants and does not make use of any shell binaries to simplify performance.

You can run the below commands directly on the console.

# Read the elements into bash array, with IFS being the de-limiter for input
IFS="," read -ra randomNos <<< "1,22,33,400,400,23,12,53"

# Print the random numbers using the '$RANDOM' variable built-in modulo with 
# array length.
printf "%s\n" "${randomNos[ $RANDOM % ${#randomNos[@]}]}"

As per the comments below, if you want to ignore a certain list of numbers from a range to select; do the approach as below

#!/bin/bash

# Initilzing the ignore list with the numbers you have mentioned
declare -A ignoreList='([21]="1" [25]="1" [53]="1" [80]="1" [143]="1" [587]="1" [990]="1" [993]="1")'

# Generating the random number
randomNumber="$(($RANDOM % 1023))"

# Printing the number if it is not in the ignore list
[[ ! -n "${ignoreList["$randomNumber"]}" ]] && printf "%s\n" "$randomNumber"

You can save it in a bash variable like

randomPortNumber=$([[ ! -n "${ignoreList["$randomNumber"]}" ]] && printf "%s\n" "$randomNumber")

Remember associative-arrays need bash version ≥4 to work.

Sign up to request clarification or add additional context in comments.

12 Comments

I don't think that arrays are portable across shells.
@123: Yes I could have done that, wanted to demo how the exact comma separated input could be turned into an outcome like this.
@TomFenech: didn't know arrays are not portable, which variant doesn't support it? Can you elaborate the same?
@Inian Fair enough
@Inian sh doesn't support arrays.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.