Created
October 24, 2016 02:11
-
-
Save princebot/0c7ecb7410509744006bd94b3756edeb to your computer and use it in GitHub Desktop.
Generate a random string of characters with Bash.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This reads a stream of random bytes from the system and drops input that isn’t | |
# a valid encoding for a letter or a number. It stops after 8 characters. | |
# | |
# Setting LC_CTYPE=C is important: Modern systems will (hopefully) be set to | |
# UTF-8, but that makes tr throw errors for illegal byte sequences. Usually, we | |
# want that kind of sane behavior — but here, we don’t. | |
LC_CTYPE=C tr -d -c '[:alnum:]' </dev/urandom | head -c 8 | |
# This saves a 15-character alphanumeric string in a variable: | |
random=$(LC_CTYPE=C tr -d -c '[:alnum:]' </dev/urandom | head -c 15) | |
# Instead of letters and numbers, this reads all printable characters. We can | |
# use it to make a 25-character password: | |
password=$(LC_CTYPE=C tr -d -c '[:print:]' </dev/urandom | head -c 25) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment