Here a method to generate n random strings of random min length to max length:
It reads a stream of random [:alnum:] alphanumeric characters; each time with a different random amount, and store it in an array.
This method maximizes efficiency with:
- The use of Bash's built-in functions.
- A single call to external command
tr.
- Reading random unsigned bytes from the
/dev/urandom fast random generator device.
#!/usr/bin/env bash
# count: Number of strings to generate
# l_min: Minimum length of string
# l_max: Maximum length of string
declare -i count=10 l_min=4 l_max=8
# Array containing random strings
declare -a rand_strings=()
declare -i i=0
while [ $i -lt $count ]; do
declare -i l=$((RANDOM%(l_max-l_min+1)+l_min))
read -r -N $l rand_strings[i]
i=$((i+1))
done < <(
LC_ALL=POSIX
tr -dc '[:alnum:]' </dev/urandom
)
printf '%d ranndom strings of %d to %d characters\n' $count $l_min $l_max
printf '%q\n' "${rand_strings[@]}"
Sample output:
10 ranndom strings of 4 to 8 characters
4QeeD9oT
GZQ7dD0
r3wb5D
17HBZhp
SP1i
t1OHq
1L4qpz7T
F5zG
Dw9HQ
ysG2chf