1

I'm attempting to setup postgres 9.6 on ubuntu/vagrant through a provisioning script. Part of my script adds a line to pg_hba.conf with the following command:

sudo -u postgres echo "host all all all md5" >> /etc/postgresql/9.6/main/pg_hba.conf

However, this gives me the error -bash: /etc/postgresql/9.6/main/pg_hba.conf: Permission denied

Which is strange because I am allowed to edit the file with either sudo nano or sudo -u postgres nano.

Here are the permissions on the file: -rw-r----- 1 postgres postgres 4641 Apr 6 16:11 pg_hba.conf

How can I add this line to my configuration file in a script?

3
  • Your sudo is covering the echo, but not the >>. If you quote the whole thing, it should work better. Commented Apr 6, 2017 at 16:25
  • Does echo "host..." | sudo tee -a filename work? Commented Apr 6, 2017 at 16:25
  • @MikeSherrill'CatRecall' that seems to work. Would you add an answer so that I can credit you? Commented Apr 6, 2017 at 16:31

1 Answer 1

1

The problem here is that redirection happens before command execution. So the redirection doesn't have the elevated privileges you expected it to.

There's more than one way around that problem. I generally use something like this.

echo "host..." | sudo tee -a /etc/postgresql/9.6/main/pg_hba.conf

Piping to sudo tee... avoids problems with quoting.


How bash executes commands

Redirections

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

Comments

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.