Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

psql return code if zero rows found

I would like for my psql command to fail if zero rows are found:

psql -U postgres -d db -c "select * from user where id=1 and name='Joe';"

I want to be able to check the return value. Return 0 from the process(!) if at least one row exists and return non-zero from the psql process if no such row exists. How can I set a return code if no rows are found?

like image 949
eatonphil Avatar asked Sep 11 '25 10:09

eatonphil


1 Answers

I don't think psql can do it by itself, but if you just want to see if there are any rows or not with the exit status you could combine it like

psql -U postgres -d db -t -c "select * from user where id=1 and name='Joe'" | egrep .

That will cause egrep to exit with non-zero if it cannot match anything. The -t will make it not print the column headers and summary information, so you may need to tweak this command line if you need that stuff.

like image 190
Eric Renouf Avatar answered Sep 13 '25 00:09

Eric Renouf