5

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.

  • 1
    As far as I understand the manual "read their argument(s) and evaluate them as a boolean expression" you can only use \if :store and that requires store to contain something that can be converted to a boolean. Plus the manual also says: "A conditional block must begin with an \if and end with an \endif" – a_horse_with_no_name May 23 '18 at 20:33
  • @a_horse_with_no_name someone figured it out. =) – Evan Carroll May 26 '18 at 4:33
7
+100

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
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.