I’ve become quite interested in the process of producing random passwords. I’d like to write my own Linux script to generate passwords! Can you offer me an example?
Congrats on wanting to write a program rather than find someone else’s solution already canned and ready to go. Of course, I’ll be showing you a script that does exactly what you want, but if I explain my thinking and logic, I bet you can take the concepts I outline and produce a new script that better fits your needs, so we’re good. 🙂
As with any program, the first and most important step is to think through the problem. Developers always talk about “divide and conquer” and it really is a critical part of any software development. In this instance, generating a complex and random password starts with the ability to generate a random character value. The pool or set of available characters can be enumerated, but how do you choose one at random?
Turns out that randomization is a big issue and there are computer science folk who spend a lot of time analyzing how random a random number generator truly is. Most end up having patterns if you look really closely, but for something of this nature, we should be okay with the built-in Linux shell $RANDOM feature. Never heard of it? It’s a “magic” variable that has a different – random – value every time you reference it!
Try this for yourself:
25173 30854 3683
Turns out that the value it produces is between 1 and MAXINT (generally 2**16), so just about every time you see it used in a shell script, it’ll be with the modulus function: $(( $RANDOM % 100 )) produces a random number between 0-99, for example.
The other important piece of this particular puzzle is to know about the slick shell substring notation. If you’ve been struggling to get the first character of a string variable, or character #4, say, you’ll love this: ${variable:start:length} can be used anywhere you use a variable reference! First character? ${variable:0:1} does the trick.
Put these two together and you have most of what you need for a quick random password generator. Let’s just set the pool of available values to be all upper case, all lower case and all digits:
okay=”ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789″
Here’s the code I would write to solve this interesting problem:
ltrs=${#okay}
while [ $length -ge 0 ] ; do
letter=”${okay:$RANDOM % $ltrs:1}”
result=”$result$letter”
length=$(( $length – 1 ))
done
echo “Result: $result”
A few quick invocations and we can see it’s working great:
Result: qay4z3e2q8d
$ lazy-passwords.sh
Result: JaFIEz5zic3
$ lazy-passwords.sh
Result: kjHvyPqlgs9
Now it’s up to you to add punctuation, let users specify how long the password should be, etc. This should get you well on the road to success, however!
Pro Tip: Learning how to program shell scripts? I suggest you check out my best-selling book Wicked Cool Shell Scripts 2nd Ed for tons of fun scripts and also our Linux shell scripting help area for online tutorials too.