bash 在bash中生成随机字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10497236/
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
Generate random char in bash
提问by Lefsler
I need to generate a huge text.
我需要生成一个巨大的文本。
I'm using bash and I want to convert an integer number like 65to a char like A.
So I use random value between 0and 255(I need all the ASCII table), convert to a char and redirect to a file using >>.
But I cannot make bashinterpret the integer as a char.
Like printf("%c", 65)in C++.
But if I try this in bash, it returns 6.
我正在使用 bash,我想将一个整数转换65为一个像A. 所以我在0和之间使用随机值255(我需要所有的 ASCII 表),转换为字符并使用>>. 但我不能bash将整数解释为字符。就像printf("%c", 65)在 C++ 中一样。但是如果我在 bash 中尝试这个,它会返回 6。
回答by pizza
you need to chain it like
你需要像链子一样链接它
printf \$(printf '%03o' $((65)))
回答by Anders Lindahl
If you need to generate a huge random sequence of bytes, why not use /dev/urandom?
如果您需要生成一个巨大的随机字节序列,为什么不使用/dev/urandom呢?
$ RANDOM=$( dd if=/dev/urandom bs=1024 count=1|base64 )
1+0 records in
1+0 records out
1024 bytes (1.0 kB) copied, 0.00056872 s, 1.8 MB/s
$ echo $RANDOM
r553ONKlLkU3RvMp753OxHjGDd6LiL1qSdUWJqImggHlXiZjjUuGQvbSBfjqXxlM6sSwQh29y484
KDgg/6XP31Egqwo7GCBWxbEIfABPQyy48mciljUpQLycZIeFc/bRif0aXpc3tl5Jer/W45H7VAng
[...]
I piped the output to base64to avoid control characters that might confuse the terminal.
我通过管道传输输出以base64避免可能混淆终端的控制字符。
$ RANDOM=$( dd if=/dev/urandom bs=1024 count=1 )
or
或者
$ dd if=/dev/urandom of=outputfile bs=1024 count=1
will create a file with 1kB of random data.
将创建一个包含 1kB 随机数据的文件。

