25

I can change the postgresql user password in this way (2 steps):

$ su - postgres -c 'psql -U postgres -d postgres'
# Alter user postgres with password 'password';

Now I want to use a single line command (1 step) to change the password such as:

su - postgres -c 'psql -U postgres -d postgres -c "alter user postgres with password ''password'';"'

I heard using double single quote to escape one single quote so I added double quote '. However is shows error message:

ERROR:  syntax error at or near "password"
LINE 1: alter user postgres with password password;

Could someone let me know how to use one line of command to do this?

2
  • 8
    I actually voted this as off-topic for migration to superuser.com. It really irritates me that Stack Overflow puts my name in as someone who closevoted it for being "not a real question" when I voted to migrate it. Commented Apr 17, 2013 at 7:23
  • Then vote to reopen! Commented Sep 17, 2015 at 21:17

1 Answer 1

52

Easier if you use sudo:

sudo -u postgres psql -U postgres -d postgres -c "alter user postgres with password 'password';"

but it's possible with su too, this should work:

su - postgres -c "psql -U postgres -d postgres -c \"alter user postgres with password 'password';\""

I've used outer double quotes and escaped the inner double quotes so they pass through as part of a single call argument to su and get unescaped by the shell so the actual query text gets passed as a single arg to psql including the single-quoted password.

One of the reasons sudo is easier for this is that it uses a smarter way of executing the subprocess instead of running a second shell instance to do it. You need one less layer of shell metacharacter escaping.

Sign up to request clarification or add additional context in comments.

5 Comments

I used this as resource to try automate the provisioning of uuid extensions but am hitting problems I don't quite get. su command I am using is su - postgres -c "psql -d template1 -c \"CREATE EXTENSION \"uuid-ossp\";\"" however I am getting a syntax error similar to that if you used that command in the psql shell with the uuid-ossp unquoted. I thought I had adequately escaped my quotes. Any ideas?
Ended creating a Here Document but would still love to know how to do this as a one liner..
@markdsievers Use sudo. It's much saner, as it doesn't require an extra layer of quoting. sudo -u postgres psql -d template1 -c "..."
If it helps anyone that has issues with this and using characters like dashes in the usernames: sudo -u postgres psql -c "alter user \"username-with-dash\" with password 'password-with-dash';"
You are a life saver! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.