Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random password for postgresql in bash

I am trying to install postgresql and generate a random password for it on deployment, just for testing. Something like this:

$DBPASS=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1)
sudo -u postgres -H createuser --no-createrole --no-superuser --no-createdb $NAME
sudo -u postgres -H createdb -O $PROJECT $PROJECT
sudo -u postgres -H psql -c "alter user $PROJECT with password '$DBPASS'"

The error I get back is this:

=b3wDxlSbUymho0CmOZ4TgPylLCanKdgJ: command not found /usr/lib/postgresql/9.1/bin/createdb: option requires an argument -- 'O' Try "createdb --help" for more information.
ERROR: syntax error at or near "with password"
LINE 1: alter user with password ''

Can anyone please explain why this is happening?

like image 386
Jimmy Avatar asked Oct 16 '25 11:10

Jimmy


1 Answers

Your first line needs to be altered (variables assignments should not have a dollar sign):

DBPASS=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1)

The error also suggests that $PROJECT is not being set - what do you get if you add echo "$PROJECT - $DBPASS" after the first line?

like image 102
Josh Jolly Avatar answered Oct 18 '25 06:10

Josh Jolly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!