July 2, 2014

How to Generate Random Strings

#!/bin/sh
cat /dev/urandom | env LC_CTYPE=C tr -cd 'A-Za-z0-9' | head -c $1

That generates random strings suitable for an OAuth token and secret. The cat command reads from the argument. /dev/urandom is the random device, guaranteed to terminate unless your BSD system is low on entropy (if this is the case, you have other problems). The env command sets an environment variable for the duration of the command fragment, in this case, it forces the locale to be "C", forcing the argument to be interpreted as single-byte, by default many systems will interpret text as multibyte by default. The tr command transliterates text. The c option complements characters and the d option deletes everything not matched by the expression, which is a character class. The head command displays the first n bytes, denoted by the c option, by default it does lines.

No comments:

Post a Comment