1

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?

5
  • It works for me (PG v10 on Linux bash). Commented Nov 7, 2017 at 11:58
  • please show me what you do ( which syntax ? ) Commented Nov 7, 2017 at 12:00
  • pg_config --version PostgreSQL 9.2.13 Commented Nov 7, 2017 at 12:03
  • do you run it as root?.. I mean could it be that you wait for password or smth else instead of reading stdout?.. Commented Nov 7, 2017 at 12:03
  • As user root: x=$(su -l postgres -c "psql -c \"CREATE TABLE test (id integer)\"") Commented Nov 7, 2017 at 12:42

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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.

5 Comments

var=` su -l postgres -c "psql -c \"CREATE DATABASE graphite WITH OWNER graphite\"" ` and echo$var , still give null value
Admittedly, I didn't do it with the su -l postgres but I did do a create database, and it returned the results info the variable. Interesting. Which Linux are you on?
backtick is old way - I think $() is preferred for bash nowadays. I'm not bash expert though...
@VaoTsun -- I had no idea -- I wasn't even familar with that syntax. Thanks for the feedback.
@Hambone no worries - here are some reference: mywiki.wooledge.org/BashFAQ/082

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.