Reputation: 2610
I need to execute the following sql queries from bash/expect script what is the preferred approach to run these queries from bash script
# psql ambari -U ambari
Password for user ambari:
psql (9.2.24)
Type "help" for help.
ambari=>
ambari=>
ambari=>
ambari=> select
ambari-> sum(case when ulo = 1 then 1 else 0 end) as ulo_1,
ambari-> sum(case when ulo = 2 then 1 else 0 end) as ulo_2,
.
.
.
for access PostgreSQL we do
psql ambari -U ambari
Password for user ambari:bigdata
and when we run this ( /tmp/file include the bach of the query )
psql -U ambari -f /tmp/file ambari
we get
psql: FATAL: no pg_hba.conf entry for host "[local]", user "ambari", database "ambari", SSL off
Upvotes: 0
Views: 2817
Reputation: 37464
Use switches -c command
or -f filename
, ie.:
$ psql -U ambari -c "SELECT ... ;" ambari # > result.file
or:
$ cat file.sql
SELECT
... ;
$ psql -U ambari -f file.sql ambari # > result.file
Probably -f
as your query seems lengthy. Use > result.file
to store the query result to a file.
As for the password, store following kind of entry to .pgpass
file in user's home dir:
$ cat >> ~/.pgpass
#hostname:port:database:username:password
localhost:5432:ambari:ambari:t00M4NY53CR3t5
and set its rights to user's eyes only:
$ chmod 600 ~/.pgpass
Also, consider psql -h hostname
if the database is not running in localhost (this needs to reflect in .pgpass
entry as well).
Upvotes: 2
Reputation: 7307
I'm using this
dbhost=localhost
dbport=5432
dbuser=user
dbpass=pass
dbname=test
export PGPASSWORD="$dbpass"
dbopts="-h $dbhost -p $dbport -U $dbuser -d $dbname"
Then run sql script from file
psql $dbopts < "$path_to_sql_script"
Or from query var
query="
SELECT 1;
...
"
psql $dbopts <<< "$query"
Also pgpass can be set in special file ~/.pgpass
like this
echo "$dbhost:$dbport:$dbname:$dbname:$dbpass" > ~/.pgpass
chmod 600 ~/.pgpass
Upvotes: 2