Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get psql result in bash?

I'm trying to get the psql result in bash

echo 'SELECT * FROM fictive_table LIMIT 1;' >> /tmp/x.sql
psql --single-transaction -d dbname -f /tmp/x.sql
echo $?

This will fail but the result I get in bash is 0. Is there a problem with the logic/code?

From the manual

psql returns 0 to the shell if it finished normally, 1 if a fatal error of its own (out of memory, file not found) occurs

Update: @Andrea Spadaccini is right. This is not fatal. How can I catch it ?

like image 529
johnlemon Avatar asked Jan 27 '26 16:01

johnlemon


1 Answers

Maybe the kind of error triggered by the query is not a fatal one like the ones mentioned in the manual, i.e., you don't run out of memory and it does not get a file not found error.

Reading a bit further in the manual, I read that:

psql returns 0 to the shell if it finished normally, 1 if a fatal error of its own (out of memory, file not found) occurs, 2 if the connection to the server went bad and the session was not interactive, and 3 if an error occurred in a script and the variable ON_ERROR_STOP was set.

To catch your error you can try to:

  • set the ON_ERROR_STOP variable; or,
  • change approach, saving the query output to a file and then working with that file.
like image 138
Andrea Spadaccini Avatar answered Jan 30 '26 09:01

Andrea Spadaccini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!