0

The code i tried in bash executed by root.

#!/bin/bash
su - postgres <<EOF1 
F="$(psql -d postgres --tuples-only -P format=unaligned -c "SELECT datname FROM pg_database JOIN pg_authid ON pg_database.datdba = pg_authid.oid WHERE rolname = 'username'")"
EOF1 
echo $F

It gives output as ERROR: permission denied for relation pg_authid

But when i try

su - postgres <<EOF1 
psql -d postgres --tuples-only -P format=unaligned -c "SELECT datname FROM pg_database JOIN pg_authid ON pg_database.datdba = pg_authid.oid WHERE rolname = 'username'"
EOF1 

This prints all db of that username. Why so?

I need to store the ouput to a bash variable for further processing.

Is there any mistake or anyother way to try this out..

Thanks.

Johnbritto
  • 149
  • 2
  • 14

1 Answers1

1

The inner $(...) expression gets executed before the su part, so it will not be run as postgres but as the current user. This is probably better written as:

command="psql -d postgres --tuples-only -P format=unaligned -c \"SELECT datname FROM pg_database JOIN pg_authid ON pg_database.datdba = pg_authid.oid WHERE rolname = 'username'\""
F=$( su - postgres -c "$command" )

You could put it all together, however:

F=$( su - postgres -c "psql -d postgres --tuples-only -P format=unaligned -c \"SELECT datname FROM pg_database JOIN pg_authid ON pg_database.datdba = pg_authid.oid WHERE rolname = 'username'\"" )

I should also note that the first example that failed for you probably would not set F to anything you could read outside of the su. However, Ubuntu and I presume other modern Linux systems do not allow you to use su in this way. You should use, e.g., sudo -l -u postrges and configure /etc/sudoers appropriately for people to have permission to run psql or whatnot as the postgres user.

zerodiff
  • 1,690
  • 1
  • 18
  • 23