How to Execute PostgreSQL Commands Inside Unix Shell Scripts

by SathiyaMoorthy on March 26, 2010

Question: How do I executed PostgreSQL Commands inside a Linux / UNIX shell script?

Answer: With the help of the psql interactive terminal, you can execute the psql commands from the shell script. For this purpose, you should enable the password less login by pg_hba.conf, or .pgpass.

Syntax

psql DBNAME USERNAME << EOF
     statement 1;
     statement 2;
     .
     .
     statement n;
EOF

PostgreSQL: Executing SQL from shell scripts

Provide all the postgreSQL commands between the EOF block as shown below.

#!/bin/sh

dbname="test"
username="test"
psql $dbname $username << EOF
SELECT * FROM test;
EOF

PostgreSQL: Using variables in SQL from shell scripts

You can also use shell script variable inside the EOF block as shown below.

#!/bin/sh

dbname="test"
username="test"
wherecond="tgs"
psql $dbname $username << EOF
SELECT * FROM test WHERE col_name = '$wherecond';
EOF
Download Free eBook - Linux 101 Hacks

Get free Unix tutorials, tips and tricks straight to your email in-box.

If you enjoyed this article, you might also like..

  1. 15 Practical PostgreSQL Database Administration Commands
  2. 15 Advanced PostgreSQL Commands with Examples
  3. Unix Shell Script to Execute Oracle SQL Query
  4. How To Backup and Restore PostgreSQL Database Using pg_dump and psql
  5. Watch: Repeat Unix Commands or Shell-Scripts every N seconds
  

Vim 101 Hacks Book

{ 2 comments… read them below or add one }

1 r March 26, 2010 at 4:26 am

What about PGPASSWORD ?

2 Hariharasubramanian March 26, 2010 at 6:00 am

One more way:

psql -U -c “select * from test”;

Leave a Comment

Previous post:

Next post: