using random to generate a random string in bash

2020-02-13 05:18发布

I am trying to use the bash function RANDOM to create a random string that consists of 8 character from a variable that contains integer and alphanumeric digits (eg: var="abcd1234ABCD")

Thank you.

2条回答
时光不老,我们不散
2楼-- · 2020-02-13 05:32

Use parameter expansion. ${#chars} is the number of possible characters, % is the modulo operator. ${chars:offset:length} selects the character(s) at position offset, i.e. 0 - length($chars) in our case.

chars=abcd1234ABCD
for i in {1..8} ; do
    echo -n "${chars:RANDOM%${#chars}:1}"
done
echo
查看更多
一夜七次
3楼-- · 2020-02-13 05:51

Using sparse array to shuffle characters.

#!/bin/bash

array=()
for i in {a..z} {A..Z} {0..9}; do
    array[$RANDOM]=$i
done
printf %s ${array[@]::8} $'\n'

(Or alot of random strings)

#!/bin/bash

b=()
while ((${#b[@]} <= 32768)); do
    a=(); for i in {a..z} {A..Z} {0..9}; do a[$RANDOM]=$i; done; b+=(${a[@]})
done
tr -d  ' ' <<< ${b[@]} | fold -w 8 | head -n 4096
查看更多
登录 后发表回答