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?
Log in to psql using the postgres database login role, connecting to the postgres database. Issue the \password command to alter the passwords of the three login roles. The syntax for the \password command is \password <username>. You will be prompted to type a new password.
If you don't remember your PostgreSQL database password, you can follow the steps below to reset it to a new value: Change the authentication method in the PostgreSQL configuration file pg_hba. conf from md5 to trust and reload the configuration. You should now be able to connect to PostgreSQL with the new password.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With