How to Use Input from \prompt in a Conditional (\if) in PSQL

psql

Let's say I get value from a prompt?

\prompt 'Write [Yes] or [No]\n' store

Which does this,

Write [Yes] or [No]
Yes

I can verify I have that works,

\echo :store
Yes

But, I can't get it to work with \if

\if :store='Yes'
unrecognized value "Yes=Yes" for "\if expression": Boolean expected

\prompt's doc don't say much on this

\prompt [ text ] name Prompts the user to supply text, which is assigned to the variable name. An optional prompt string, text, can be specified. (For multiword prompts, surround the text with single quotes.)

By default, \prompt uses the terminal for input and output. However, if the -f command line switch was used, \prompt uses standard input and standard output.

Best Answer

You can accomplish this using using \gset to coerce the variable into a boolean which \if can use,

$ cat if_prompt.sql 
\prompt 'enter abc here: ' x
select ('abc' = :'x') as is_abc \gset
\if :is_abc
  \echo you can read
\else
  \echo you are illiterate or impertinent
\endif

Testing it,

$ psql test -f if_prompt.sql 
enter abc here: abc
you can read

$ psql test -f if_prompt.sql 
enter abc here: 123
you are illiterate or impertinent