Jason S Jason S - 8 months ago 37
Bash Question

How to use sudo -u on both sides of a pipe

I am doing a bit of PostgreSQL administration on OS X.
Sometimes I need to copy a database to another database, which I do as follows.

sudo -u _postgres pg_dump mydb > mydb.sql
sudo -u _postgres psql -d mydb-testing -f mydb.sql

But I would rather just do this

sudo -u _postgres pg_dump mydb | sudo -u _postgres psql -d mydb-testing

However this obviously doesn't work.

I am looking for a solution where I can run a command as the _postgres user on both sides of a pipe.


I believe

sudo -u _postgres pg_dump mydb | sudo -u _postgres psql -d mydb-testing

should work as long as you make sure that the sudos won't ask for your password from your terminal simultaneously.

If I cache my sudo password, I can pipe normally from one sudo'ed command to another:

sudo -u root echo hello world | sudo -u root tr a-z A-Z #prints HELLO WORLD

Another option is to use one sudo to spawn a shell:

sudo -u _postgres sh -c 'pg_dump mydb | psql -d mydb-testing'

( You can use a heredoc if you have lots of things to do in that shell:

sudo -u _postgres sh <<'SCRIPT' 
    pg_dump mydb | psql -d mydb-testing