Skip to main content

could not change directory to "/home/corey/scripts": Permission denied [Resolved]

I get the error message...

could not change directory to "/home/corey/scripts": Permission denied

... when I run the following script ...

#!/bin/bash
sudo -u postgres psql < setup_dev_db.sql
read -rsp $'Press any key to continue...\n' -n 1 key

... the contents of setup_dev_db.sql are executed without any issues, but the error is annoying.

Can I get rid of it?


Question Credit: Corey
Question Reference
Asked January 11, 2019
Posted Under: Unix Linux
64 views
4 Answers

To change to a directory, a user must have the 'x' permission for that directory.

I assume you are running the script from '/home/corey/scripts'. When 'sudo -u postgres' changes the current user to 'postgres' it attempts to set the working directory for 'postgres' to the working directory it was called from generating the error you're seeing.

Make sure that the user 'postgres' has permission 'x' for '/home/corey/scripts'.


credit: robartsd
Answered January 11, 2019

You may use sudo -u postgres -c your_command.bash or su postgres -c your_command.bash. You could also use,

su - postgres your_command.bash

This will ensure that you acquired all the postgres account enviroment.


credit: George Siggouroglou
Answered January 11, 2019

For me this did the trick, 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


credit: Philippe Gachoud
Answered January 11, 2019
Your Answer