Bash 使用\copy时Postgres变量替换

Bash 使用\copy时Postgres变量替换,bash,postgresql,variables,Bash,Postgresql,Variables,我正在使用psql命令\copy,我希望像编写查询脚本时一样,从shell(表名)向它传递一个变量。我在文档中读到: 该命令的语法与SQL COPY命令的语法类似。请注意,正因为如此,特殊的解析规则适用于\copy命令。特别是,变量替换规则和反斜杠转义不适用 这似乎非常确定,但是我想知道是否有人知道一种解决方法?您可以使用shell变量替换和herdoc语法。例如: #!/bin/sh tablename=foo psql -d test <<EOF \copy $tablename

我正在使用psql命令\copy,我希望像编写查询脚本时一样,从shell(表名)向它传递一个变量。我在文档中读到:

该命令的语法与SQL COPY命令的语法类似。请注意,正因为如此,特殊的解析规则适用于\copy命令。特别是,变量替换规则和反斜杠转义不适用


这似乎非常确定,但是我想知道是否有人知道一种解决方法?

您可以使用shell变量替换和herdoc语法。例如:

#!/bin/sh
tablename=foo
psql -d test <<EOF
\copy $tablename FROM '/path/to/file'
EOF
#/垃圾箱/垃圾箱
tablename=foo

psql-d test您可以使用命令行参数将变量从shell传递到psql
-v psql_var=“$shell_var”
(或者在导出后直接使用shell转义
`echo“$shell_var”`
)。然后,您可以在另一个meta命令(使用
\set
本地或使用
\gset
服务器端)中构建
\copy
meta命令。例如:

#!/bin/sh
tablename=foo
psql -d test <<EOF
\copy $tablename FROM '/path/to/file'
EOF
#/垃圾箱/垃圾箱
tablename=foo
psql-d测试-v tbl=“$tablename”