This patch adds two very simple psql commands: \quit_if and \quit_unless.
Each takes an optional string parameter and evaluates it for truthiness via ParseVariableBool().
If a true-ish value is passed to \quit_if, psql will behave as if the user had input \quit.
\quit_unless will do nothing if the value given was true-ish, and will \quit in any other circumstances.
Examples below show the behavior:
$ psql postgres
psql (10devel)
Type "help" for help.
# \quit_if
# \quit_unless
$ psql postgres
psql (10devel)
Type "help" for help.
# \quit_if f
# \quit_if 0
# \quit_if false
# \quit_if 2
unrecognized value "2" for "\quit_if"; assuming "on"
$ psql postgres
psql (10devel)
Type "help" for help.
# \quit_unless 2
unrecognized value "2" for "\quit_unless"; assuming "on"
# \quit_unless f
$
The need for this patch has arisen from several scripts I've written recently that were about 97% psql and 3% bash or similar glue language. In those scripts, there's often a test that says "there is no work to do here, and that is not an error". I could engineer an optional SELECT 1/0 to generate an error, but then I have to make the bash script determine whether that was an error-error or a no-everything-is-ok-error. I also don't want to wrap hundreds of lines of SQL inside python docstrings (thus losing syntax highlighting, etc) just to handle one if/then.
Many thanks to Pavel Stehule for brainstorming this one with me.