Random element of an array in bash
Created by A. Martínez on 2019-05-10
4z.com
Table des matičres
Random element of an array in bash
This document aims at explaining how to access to a random element of an array in Bash.
The first thing to do is to define the elements of an array.
In Bash, we can do this easily:
my_array[0]="Spain"
my_array[1]="Switzerland"
my_array[2]="France"
my_array[3]="Germany"
my_array[4]="Italy"
my_array[5]="Portugal"
my_array[6]="Ireland"
my_array[7]="Serbia"
We have defined the "my_array" array and filled eight elements (from "[0]" to "[7]"). We can access the values of the elements:
echo ${my_array[0]}
echo ${my_array[4]}
echo ${my_array[7]}
If we want to print all the elements of the array:
echo ${my_array[*]}
In the other hand, if we need to retrieve the length of the array:
echo ${#my_array[@]}
The "RANDOM" variable is very useful in Bash. Every time it is printed (or referenced in general), it will show a random integer between 0 and 32767:
echo $RANDOM
We will take profit from this variable in order to select randomly an element of the array.
The modulo operator "%" gives the reminder after the division of one number by another. Let us see this in an example:
echo $((9%2))
echo $((9%3))
echo $((9%7))
The modulo operator will help us to retrieve numbers in a delimited range.
Note that the "$(( ))" just accounts for an arithmetic expansion in Bash, in order to translate a string into a numerical expression.
Now we are ready to access randomly an element of an array.
First of all, we need to retrieve the length of the array as above explained:
echo ${#my_array[@]}
We know that this length is 8, so we need to create a variable which each time we reference it, it gives to us a random number between 0 and 7. We can do this profiting from the "RANDOM" variable and from the modulo operator "%":
echo $((RANDOM%8))
Recall that if we do a division by 8, all the possible reminders will be between 0 and 7.
We create the intermediate variable "rand" to store this value, and then, we print the array element for this index position:
rand=$((RANDOM%8)) && echo ${my_array[$rand]}
We can see that values of the array are printed randomly.
Note that the "&&" just means that we will execute the second command once the first one has ended successfully.
Define an array of 13 elements with names of important cities around the world.
Repeat all the steps of this document for the new case.
Provide images of all the steps.