How to pass environment variables to a sql file from bash shell (PostgreSQL)
This will allow you to do it.  In your case, everything between '$$' is a &quot;dollar-quoted string constant, so nothing gets interpreted.  See sql syntax, 4.1.2.4.
\set CREDO 'begin create user ' :dbuser '; exception when duplicate_object then raise notice ''user already exists''; end';
do :'CREDO';