Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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. –  Eric DANNIELOU Nov 9 '12 at 13:30
add comment

2 Answers

up vote 3 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. –  SvW 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 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 4:26
add comment

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
add comment

Your Answer

 
discard

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.