Scripting htdigest -c /path/to/file/$user $user $password in Bash


The easiest method, based on one of the suggestions in the top-voted answer, is probably this:

digest="$( printf "%s:%s:%s" "$user" "$realm" "$password" | 
           md5sum | awk '{print $1}' )"

printf "%s:%s:%s\n" "$user" "$realm" "$digest" >> "/etc/apache2/pw/$user"

I've used md5sum from GNU coreutils and awk rather than just md5 because it's what i have installed on my system and I couldn't be bothered finding out which package contains /usr/bin/md5 - you could also use sha512sum or other hashing program.

e.g. if user=foo, realm=bar, and password=baz then the command above will produce:


htdigest doesn't do anything magical or even unusual - it just outputs the user, realm, and password in the right the command above does.

Deleting the digest for a given user:realm instead of just adding one, can easily be done with sed.

sed -i -e "/^$user:$realm:/d" "/etc/apache2/pw/$user"

And updating/changing the digest for a user:realm can also be done with sed in combination with the method above to generate the digest line. e.g.

digest="$( printf "%s:%s:%s" "$user" "$realm" "$new_password" | 
           md5sum | awk '{print $1}' )"

sed -i -e "/^$user:$realm:/ c$user:$realm:$digest" "/etc/apache2/pw/$user"