14

I want to set a password for the default Postgresql server user, postgres. I did it by using:

sudo -u postgres psql
# \password postgres

I want to do this step in many machines, so I would like to create a bash script to do the same. How to accomplish this in bash?

saji89
  • 255

2 Answers2

30

Instead of using the psql \password command, which expects an interactive terminal, you can use:

ALTER USER postgres WITH PASSWORD 'newpassword';

Say, via a psql -c command:

sudo -u postgres psql -c "ALTER USER postgres WITH PASSWORD 'newpassword';"
Craig Ringer
  • 11,525
10

As documented you can run meta-commands via the --command option.

sudo -u postgres psql --command '\password postgres'

The single quotes ensure that the shell doesn't treat the backslash as an escape-character.

Ansgar Wiechers
  • 4,267
  • 2
  • 19
  • 26