Re: Having trouble passing a shell variable to a query from psql command line

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
Cc: Murthy Nunna <mnunna(at)fnal(dot)gov>, Pgsql-admin <pgsql-admin(at)lists(dot)postgresql(dot)org>
Subject: Re: Having trouble passing a shell variable to a query from psql command line
Date: 2025-08-29 18:16:21
Message-ID: 2335799.1756491381@sss.pgh.pa.us
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-admin

"David G. Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com> writes:
> On Fri, Aug 29, 2025 at 10:52 AM Murthy Nunna <mnunna(at)fnal(dot)gov> wrote:
>> psql -d mydb -t -A -c "SELECT relkind FROM pg_class WHERE relname =
>> :'SHELL_VAR' ;" -v SHELL_VAR="$SHELL_VAR"
>>
>> ERROR: syntax error at or near ":"
>>
>> LINE 1: SELECT relkind FROM pg_class WHERE relname = :'SHELL_VAR' ;

> I provide the documentation. Under psql -c:
> "command must be either a command string that is completely parsable by the
> server (i.e., it contains no psql-specific features)"

Yeah. The argument of a -c switch is just sent to the server as-is.

However, you don't need a script file to fix this. You can do
something like

echo "SELECT relkind FROM pg_class WHERE relname = :'SHELL_VAR' ;" | psql -d mydb -t -A -v SHELL_VAR="$SHELL_VAR"

regards, tom lane

In response to

Responses

Browse pgsql-admin by date

  From Date Subject
Next Message Ron Johnson 2025-08-29 18:27:49 Re: Having trouble passing a shell variable to a query from psql command line
Previous Message David G. Johnston 2025-08-29 17:58:03 Re: Having trouble passing a shell variable to a query from psql command line