Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
Upvoted the question : Many questions on Server Fault 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. – user130370 Nov 9 '12 at 13:30
up vote 4 down vote accepted

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.

share|improve this answer
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 9 '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 9 '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 9 '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 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 4:26

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';"
share|improve this answer
WITH, not SET (15 chars) – ChocoDeveloper Jun 17 '13 at 14:59
@ChocoDeveloper Gah. Thanks. – Craig Ringer Jun 17 '13 at 23:33

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.