King David
King David

Reputation: 540

how to insert PostgreSQL result to a shell variable

I want to set all this syntax in variable

su -l postgres -c "psql -c \"CREATE DATABASE graphite WITH OWNER graphite\""

CREATE DATABASE 

so I wrote this

res=$(  su -l postgres -c "psql -c \"CREATE DATABASE graphite WITH OWNER graphite\"" )

CREATE DATABASE 

but $res is empty

echo $res

I also tried to add " " but without success.

How to insert the results of

su -l postgres -c "psql -c \"CREATE DATABASE graphite WITH OWNER graphite\""

to a shell variable?

Upvotes: 1

Views: 793

Answers (2)

Vao Tsun
Vao Tsun

Reputation: 51446

checking the resulting exit state works:

MacBook-Air:~ root# res=$(su -l vao -c "/usr/local/Cellar/postgresql/9.6.1/bin/psql -c \"CREATE DATABASE graphite\" -d so")
MacBook-Air:~ root# echo $?
0
MacBook-Air:~ root# res=$(su -l vao -c "/usr/local/Cellar/postgresql/9.6.1/bin/psql -c \"CREATE DATABASE graphite\" -d so")
ERROR:  database "graphite" already exists
MacBook-Air:~ root# echo $?
1

and the stdout shows as well:

MacBook-Air:~ root# echo $res
Timing is on. Pager usage is off. SET Time: 0.333 ms SET Time: 0.112 ms SET Time: 0.127 ms Time: 0.290 ms

Upvotes: 1

Hambone
Hambone

Reputation: 16377

This is a more generic answer, but backticks (`) will put the results of any shell command into a variable:

$ foo=`psql -d postgres -c "select 'Hello'"`
$ echo $foo
?column? ---------- Hello (1 row)

That said, I'm curious why you would want the results of a create database command in a shell variable. I'm sure there's a good reason, I just never would think to do such a thing.

Upvotes: 0

Related Questions