0

I'm trying to generate a random password with this small script

#!/bin/bash if [ -z $PASSWORD ]; then PASSWORD=$(date | md5sum | grep '[a-zA-Z1-9]') fi

But this results in a result like :

15d020e6e8e6038ffb027323401ca9a9 -

My password field cannot have any empty space or symbols, I want to use standard bash commands because this is will be executed in bare docker environments.

How do I fix this? I tried grep -o but didn't work.

Freedo
  • 1,255

2 Answers2

2
PASSWORD=$(date | md5sum | grep -o '[a-z0-9]*')

man grep:

>    Repetition
>        A  regular  expression  may  be  followed  by one of several repetition
>        operators:
>        ?      The preceding item is optional and matched at most once.
>        *      The preceding item will be matched zero or more times.

ps.: this is very unsecure password generation. Better to use pwgen or mkpasswd.

Ipor Sircer
  • 14,546
  • 1
  • 27
  • 39
1

There are several ways to parse out the actual digest out from the output of md5sum:

  1. grep -E -o '[[:alnum:]]+', this would return the alphanumeric part of the md5sum output, but would also give you any filename bits if present in the output (not in the case presented in the question, as the filename is -, standard input).
  2. cut -d ' ' -f 1, this would simply return the bit of the output before the first space character. This is arguably the most common way to get at the "naked" MD5 digest string.
  3. Variations on the cut theme includes awk '{ print $1 }' and similar things.

For password generation, I would suggest using pwgen rather than an MD5 digest, mostly because an MD5 digest, unless computed over random data, is not random.

A hack would be to use something like

tr -dc '[:alnum:]' </dev/urandom | dd bs=1 count=32 2>/dev/null

This would extract a stream of alphanumeric characters from /dev/urandom and dd would cut the stream off after 32 such characters. Instead of dd, one could also use head -c 32.

Or, using md5sum (in this case over 1Kb of random data from /dev/urandom):

dd if=/dev/urandom bs=1k count=1 | md5sum | cut -d ' ' -f 1

But really, just install and use pwgen.

See also When to use /dev/random vs /dev/urandom

Kusalananda
  • 333,661