8

Is there any way to capture shell output (in a psql variable) and/or the exit code of running a shell command from inside psql using \!? The documentation provides no details.

3 Answers 3

4

Using \! with \i..

You can combine the two like this,

  • \! echo "SELECT 1;" > bar (runs the command echo "SELECT 1;" redirects output of SELECT 1; to bar)
  • \i bar (runs the commands in bar)
Sign up to request clarification or add additional context in comments.

Comments

1

Seems to be impossible for \!,

but one can set a variable from external command output,

testdb=> \set content `cat my_file.txt`

and then using this var in sql expression like this:

testdb=> INSERT INTO my_table VALUES (:'content');

Comments

-1

You can use \o <filename> option to specify the output file or use COPY command to solve your problem.

6 Comments

I'm not sure how \o helps. If I am running a shell command, I can always redirect its output to a file. Also not sure how COPY helps. I'm not trying to load data.
well, I guess it depends what you are trying to achieve, for bulk ddl updates I used \o a lot. I guess it's not your case.
this might be what you are looking for
The SO question you point to is about capturing SQL output from psql. I want to capture shell output and exit code in psql.
I can capture the shell exit status of psql but I see no documentation for how to capture the exit status of whatever is run via \!. Do you?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.