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
  • 1
  • 2
  • 8
  • Upvoted the question : Many questions on [SF] can be learnt from documentation, books, websites... The person who downvoted you will not teach you to use the `man` command. Please be sure to try `man psql` in the future. –  Nov 09 '12 at 13:30

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
  • 10,553
  • 9
  • 38
  • 59
  • WITH, not SET (15 chars) – ChocoDeveloper Jun 17 '13 at 14:59
  • It's sad that the \password command does not have a non-interactive method. I can understand the reasoning (hard to call it safely on the client), but the end effect is that people use the ALTER ROLE command which sends the password in the statement unencrypted (which is the major advantage of `\password` or `createuser -E -P`. – eckes Sep 17 '20 at 19:42
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,197
  • 2
  • 17
  • 26
  • Thanks, I just did the same, but with a minor difference: `sudo -u postgres psql --command "\password"`. Wondering, why my question was downvoted. – saji89 Nov 09 '12 at 12:28
  • @saji89: It's not my downvote, but I guess because this can be easily learned by reading the documentation. – Sven Nov 09 '12 at 12:34
  • @saji89 When you use double quotes, the shell treats the backslash as an escape-character, i.e. as an instruction to treat the next character as a literal rather than a special character. To get a literal backslash inside double qoutes you have to use `"\\..."`. – Ansgar Wiechers Nov 09 '12 at 12:49
  • @AnsgarWiechers, Thanks for that correction. But the funny part is that that line is working for me. From what I read at http://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html It says: `The backslash retains its special meaning only when followed by one of the following characters: ‘$’, ‘\`’, ‘"’, ‘\’, or newline.` I think that is why `"\password"` worked fine. – saji89 Nov 10 '12 at 04:26