Script to modify htpasswd without Apache

This is a handy script I have written for an environment where I needed to modify a htpasswd file without Apache being installed on the server (Where openssl is installed). The script first verifies if the new user exists already, if it does it will delete the line containing the username first before creating the new one – Otherwise it will just create a new user.

#!/bin/bash

# Set the htpasswd file
htpasswd="/scripts/htpasswd"

echo "Enter the Username for the new htpasswd user:"
  read user
  # Check to see if the user exists in htpasswd already
  if [[ $(cat $htpasswd) == *"$user"* ]];then
    read -p "This user already exists, would you like to update their password (y/n)?" yn
    case $yn in
        # If yes, continue. Else, exit
        [Yy]* ) :;;
        [Nn]* ) exit;;
        * ) echo "Please answer yes or no.";;
    esac
  else
    :
  fi
echo "Now the password (Less than 8 characters)?"
  read pass
    if [[ ${#pass} -ge 9 ]];then
      echo "Please enter a password less than 8 characters"
      read pass
    else
      :
    fi

# Create the User
echo "Now creating the User"
# Delete the user if they exist in the file (User has confirmed)
sed -i "/^$user\:/d" $htpasswd
echo "$user:$(openssl passwd -crypt $pass)\n" >> $htpasswd

Make the script executable and run it as follows:

./add-htpasswd-user.sh

Any comments or questions? Get in touch here or Email me at [email protected]