| 1 | #!/bin/bash |
| 2 | # |
| 3 | # |
| 4 | # Random password generator for Bash 2.x + |
| 5 | #+ by Antek Sawicki <[email protected]>, |
| 6 | #+ who generously gave usage permission to the ABS Guide author. |
| 7 | # |
| 8 | # ==> Comments added by document author ==> |
| 9 | |
| 10 | |
| 11 | MATRIX="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" |
| 12 | # ==> Password will consist of alphanumeric characters. |
| 13 | LENGTH="8" |
| 14 | # ==> May change 'LENGTH' for longer password. |
| 15 | |
| 16 | |
| 17 | while [ "${n:=1}" -le "$LENGTH" ] |
| 18 | # ==> Recall that := is "default substitution" operator. |
| 19 | # ==> So, if 'n' has not been initialized, set it to 1. |
| 20 | do |
| 21 | PASS="$PASS${MATRIX:$(($RANDOM%${#MATRIX})):1}" |
| 22 | # ==> Very clever, but tricky. |
| 23 | |
| 24 | # ==> Starting from the innermost nesting... |
| 25 | # ==> ${#MATRIX} returns length of array MATRIX. |
| 26 | |
| 27 | # ==> $RANDOM%${#MATRIX} returns random number between 1 |
| 28 | # ==> and [length of MATRIX] - 1. |
| 29 | |
| 30 | # ==> ${MATRIX:$(($RANDOM%${#MATRIX})):1} |
| 31 | # ==> returns expansion of MATRIX at random position, by length 1. |
| 32 | # ==> See {var:pos:len} parameter substitution in Chapter 9. |
| 33 | # ==> and the associated examples. |
| 34 | |
| 35 | # ==> PASS=... simply pastes this result onto previous PASS (concatenation). |
| 36 | |
| 37 | # ==> To visualize this more clearly, uncomment the following line |
| 38 | # echo "$PASS" |
| 39 | # ==> to see PASS being built up, |
| 40 | # ==> one character at a time, each iteration of the loop. |
| 41 | |
| 42 | let n+=1 |
| 43 | # ==> Increment 'n' for next pass. |
| 44 | done |
| 45 | |
| 46 | echo "$PASS" # ==> Or, redirect to a file, as desired. |
| 47 | |
| 48 | exit 0 |