Skip to content

Instantly share code, notes, and snippets.

@kenny-evitt
Last active May 30, 2021 19:05
Show Gist options
  • Save kenny-evitt/dd19436759085d30f3d0def125a7f8fb to your computer and use it in GitHub Desktop.
Save kenny-evitt/dd19436759085d30f3d0def125a7f8fb to your computer and use it in GitHub Desktop.
Generate a random string, e.g. for passwords, using specific characters only, from a Unix/Linux command line shell using the *head* and *tr* programs
head /dev/urandom | tr -dc 'A-Za-z0-9!@#$%^&*()' | head -c 32 && echo
# With all of the OWASP password special characters, based on [this comment](http://unix.stackexchange.com/questions/230673/how-to-generate-a-random-string/230676#comment525492_230676) from the U&L SE question answer referenced below:
head /dev/urandom | tr -dc 'A-Za-z0-9!"#$%&'\''()*+,-./:;<=>?@[\]^_`{|}~' | head -c 32 && echo
# This was adapted from [this answer](http://unix.stackexchange.com/a/230676/56148) to the Unix & Linux Stack Exchange question [password - How to generate a random string? - Unix & Linux Stack Exchange](http://unix.stackexchange.com/questions/230673/how-to-generate-a-random-string).
# The original command:
head /dev/urandom | tr -dc A-Za-z0-9 | head -c 13
# The *tr* program will "translate or delete characters". The `-dc` option will delete characters in the complement of the following set specified, in this case the set specified as `A-Za-z0-9` being uppercase and lowercase (Latin) letters and the numerals.
# The *head* program will "output the first part of files". The `-c` option will cause *head* to print the first specified number of bytes of each file.
# In the Terminal app on macOS:
# > ```
# > (ins)Feynman:~ kenny$ head /dev/urandom | tr -dc 0-9 | head -c 4
# > tr: Illegal byte sequence
# > ```
# This worked:
head /dev/urandom | LC_ALL=C tr -dc 0-9 | head -c 4
# The `LC_ALL` environment variable overrides all of the locale environment variables as described in `man environ`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment