在 bash 中使用 random 生成随机字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32484504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
using random to generate a random string in bash
提问by Dimareal
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")
我正在尝试使用 bash 函数 RANDOM 从包含整数和字母数字数字的变量中创建一个由 8 个字符组成的随机字符串(例如:var="abcd1234ABCD")
Thank you.
谢谢你。
回答by choroba
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}
是可能的字符数,%
是模运算符。${chars:offset:length}
选择位置处的字符offset
,即在我们的例子中 0 - length($chars)。
chars=abcd1234ABCD
for i in {1..8} ; do
echo -n "${chars:RANDOM%${#chars}:1}"
done
echo
回答by bac0n
Using sparsearray 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
回答by insign
If opensslis available, here is a way:
如果openssl可用,这是一种方法:
openssl rand -base64 12 # return
rand=$(openssl rand -base64 12) # saves to var
sed "s/[^a-zA-Z0-9]//g" <<< $(openssl rand -base64 17) # leave only letters and numbers
# The last command can go to a var too.
OPTION 2- No specific length (best)
选项 2- 无特定长度(最佳)
sed "s/[^a-zA-Z0-9]//g" <<< $(cat /dev/urandom | tr -dc 'a-zA-Z0-9!@#$%*()-+' | fold -w 32 | head -n 1)
回答by Denis Ryzhkov
For those looking for a random alpha-numeric string in bash:
对于那些在 bash 中寻找随机字母数字字符串的人:
tr -dc A-Za-z0-9 </dev/urandom | head -c $LENGTH
tr -dc A-Za-z0-9 </dev/urandom | head -c $LENGTH
The same as a well-documented function:
与记录良好的函数相同:
function rand-str {
# Return random alpha-numeric string of given LENGTH
#
# Usage: VALUE=$(rand-str $LENGTH)
# or: VALUE=$(rand-str)
local DEFAULT_LENGTH=64
local LENGTH=${1:-$DEFAULT_LENGTH}
tr -dc A-Za-z0-9 </dev/urandom | head -c $LENGTH
# -dc: delete complementary set == delete all except given set
}