たのもう

MacOS X でランダムな英数字を生成したいんです。
もちろん、pwgen というコマンドがあるのは知っていますが、今回はpwgenは使わない方法を模索します。

技あり!を取られた気分

こんな感じで

cat /dev/urandom | tr -dc A-Za-z0-9 | fold -w32 | head -n1

いけるはず…

ところが…

$ cat /dev/urandom | tr -dc A-Za-z0-9 | fold -w32 | head -n1
tr: Illegal byte sequence

お…技ありを取られた気分。
なぜ、こんな事が起こるかについては、以下の記事に書かれていました。

I'm brand new to UNIX and I am using Kirk McElhearn's "The Mac OS X Command Line" to teach myself some commands. I am attempting to use tr and grep so that I can search for text strings in a regu...

unix.stackexchange.com

Computers store data as sequences of bytes. A text is a sequence of characters. There are several ways to encode characters as bytes, called character encodings. The de facto standard character encoding in most of the world, especially on OSX, is UTF-8, which is an encoding for the Unicode character set. There are only 256 possible bytes, but over a million possible Unicode characters, so most characters are encoded as multiple bytes. UTF-8 is a variable-length encoding: depending on the character, it can take from one to four bytes to encode a character. Some sequences of bytes do not represent any character in UTF-8. Therefore, there are sequences of bytes which are not valid UTF-8 text files.
tr is complaining because it encountered such a byte sequence. It expects to see a text file encoded in UTF-8, but it sees binary data which is not valid UTF-8.

cat /dev/urandomtr が期待しない文字列(UTF-8 では無い文字列)が流れてきているからとのことです。

ということで、一本

こんな感じで

$ export LC_ALL=C; cat /dev/urandom | tr -dc A-Za-z0-9 | fold -w32 | head -n1
2u8uJ3zweCwHAvRjTsIYUKjXGG9KId5y

有難うございました

I'm brand new to UNIX and I am using Kirk McElhearn's "The Mac OS X Command Line" to teach myself some commands. I am attempting to use tr and grep so that I can search for text strings in a regu...

unix.stackexchange.com

やっぱり、pwgenが良い気がしました。

元記事はこちら

小ネタ道場一本勝負 〜 MacOS X でランダムな英数字を生成する 〜