psql return code if zero rows found

霸气de小男生 提交于 2019-12-02 21:31:25

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/29948334/psql-return-code-if-zero-rows-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!