16

Recently updated from Postgresql 9.1 to 9.3.

Everything works fine, but I noticed now when I type in:

sudo -u postgres psql

I am getting hit with a permission denied error for changing dir to root.

"Could not change directory to /home/root.

However, when I use:

sudo su - postgres 
psql

It accesses it fine. How can I fix this?

3 Answers 3

22

change directory to someplace that postgres has access to:

cd /tmp
sudo -u postgres psql
3
  • Why then does su work? It should have access to the dir, or I should get the same error, should I not?
    – Johnathan
    Mar 4, 2016 at 19:03
  • I don't know. I went through this post to figure it out stackoverflow.com/questions/4598001/… and i couldn't find a difference that made sense. Mar 4, 2016 at 21:12
  • See my answer. sudo su postgres will give you similar errors.
    – DylanYoung
    Jul 17, 2017 at 13:39
20

Try this:

sudo -i -u postgres psql

This accomplishes (almost) the same thing as your

sudo su - postgres 

The - in the above indicates that you want to use the postgres account's environment. If you remove the -, it will fail similarly to sudo -u

The -i indicates that you want to run the postgres account's login shell (hence cding to their home directory).

0

For me this did the trick (or you'll get a could not change directory to "/root": Permission denied), pay attention to quotes (')

sudo -Hiu postgres 'pg_dump --column-inserts --data-only --table=someTable entities_db > /var/backups/anywhere/$(date +%Y%m%d_%H%M%S)_someTable.sql'

Note the -Hiufor sudo, or use su - postgres

you can also put that in a cronjob for root with crontab -e

Your Answer

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

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