使用“$RANDOM"在 Bash 中生成随机字符串 [英] Using "$RANDOM" to generate a random string in Bash

查看:29
本文介绍了使用“$RANDOM"在 Bash 中生成随机字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Bash 变量 $RANDOM 从包含整数和字母数字数字的变量中创建一个由 8 个字符组成的随机字符串,例如,var=abcd1234ABCD";.

I am trying to use the Bash variable $RANDOM to create a random string that consists of 8 characters from a variable that contains integer and alphanumeric digits, e.g., var="abcd1234ABCD".

我该怎么做?

推荐答案

使用参数扩展.${#chars} 是可能的字符数,% 是取模运算符.${chars:offset:length} 选择位置 offset 处的字符,即在我们的例子中为 0 - length($chars).

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

这篇关于使用“$RANDOM"在 Bash 中生成随机字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆