10

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.

2
  • 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"
    – user1822
    May 23, 2018 at 20:33
  • @a_horse_with_no_name someone figured it out. =) May 26, 2018 at 4:33

1 Answer 1

13
+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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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