Logo  

CS469 - Linux and Unix Administration and Networking

Displaying exercises/e5/solution/f.sh

#!/bin/bash

# Make a random password generator: read 3 to 5 random lines from
# /usr/dict/words and assemble them together to form a random password.
# It should also take an optional minimum size argument that insures the
# password generated is of a minimum length. Additional the first letter of each
# word is should be capitalized.
# You may not use the shuf command for this assignment, use sed with the -n
# option and the p command (sed -n ##p /usr/dict/words)
# Example output:
# > ./f.sh
# UnfairDestructivenessTheologyCornfield

# Assign a variable with a random value between 3 and 5:
let words=(RANDOM%3+3);

# Find the number of lines in /usr/dict/words and store that in a variable
let ds=$(wc -l /usr/dict/words | cut -f 1 -d ' ');

# Initialize a variable to be the value of the first command line parameter
# or 1 by default (the minimum length)
let min=${1:-1};

# Initialize a variable to be an empty string:
pass="";

# Loop from 0 to the number of words you've picked and until the minimum length
# is reached:
for((i=0; i < words || ${#pass} < min ; i++)) {
  # Use RANDOM to pick a random line # into /usr/dict/words
  let "wp=(RANDOM|RANDOM<<15)%ds";

  # Use sed to get the word at that line number in /usr/dict/words
  word=$(sed -n ${wp}p /usr/dict/words);

  # append the word (capitalizing the first letter) to the empty string you
  # defined outside of the loop
  pass="${pass}${word^}";
}

# Print the generated password:
echo $pass;