Updated Bash Script To Provide Read Only Postgres Database Table Access

I wrote an article a couple weeks ago regarding a shell script to run that would provide a postgres user read only access to every table in a specific database. Tonight I was updating a over a dozen databases and needed to provide read only access to all of them to a specific user so I decided to update the bash script from a couple of weeks ago to take a couple variables from the shell so you could specify database and user. The new script along with instructions on how to use it are below.

Bash Script To Provide Read Only Access To Every Table In A PostgreSQL Database:

#!/bin/sh
#
# Provide Read Only Access On PostgreSQL Database
# Use: ./pgaccess $database $username
#

tables=$(psql $1 -A -t -c "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';")

for table in $tables
do
echo "Providing select to $2 on $table"
psql $1 -c "GRANT SELECT ON $table to $2;"
done

As you can see there are now two variables required to run the script which are database and username. The script above should be run in the below format. I name the script pgaccess.sh so that is what is used in the example below.

Read Only User Script Syntax:

./pgaccess $database $username

Just replace $database with the name of the database you are providing access to and replace $username with the name of the user that will be provided SELECT access to the PostgreSQL database.


List Price: $36.99 USD
New From: $36.08 USD In Stock
Used from: $13.93 USD In Stock

PostgreSQL 8.4 Official Documentation - Volume IV. Reference (Paperback)

By (author): The PostgreSQL Global Development Group


List Price: $35.99 USD
New From: $22.36 USD In Stock
Used from: $5.94 USD In Stock

Share