【问题标题】:error syntax ( execute psql query from shell script )错误语法(从 shell 脚本执行 psql 查询)
【发布时间】:2013-01-18 13:24:51
【问题描述】:

我希望在我的第二台服务器上远程执行此查询,并且

#!/bin/bash
QUERY=`psql -h my2ndserverip  -d testdb -U testuser  'select count(*) as result   
from testdb.user  where last_logged_date > (clock_timestamp()  -interval '90    minutes)
 echo "users = $QUERY" > tmp.txt

修复语法的任何提示?

【问题讨论】:

  • 不确定是不是唯一的引号
  • 当然,但这将是一个优秀的开始。
  • 太棒了,你能指出我错过引号的地方吗?

标签: postgresql shell psql


【解决方案1】:

使用here文档(heredocuments保留引号并允许shell变量替换,如参数90所示,在单引号内使用):

#!/bin/bash

limit=${1:-90}

psql -h my2ndserverip  -d testdb -U testuser -t -A <<EOFEOF > tmp.txt
  SELECT count(*) AS result   
  FROM "user"  
  WHERE last_logged_date > clock_timestamp()-interval '${limit} minutes'
  ;
EOFEOF

exitcode=$?
result=`cat tmp.txt`

echo "Limit=${limit} Exitcode=${exitcode} Result=${result}"
#Eof

我想你希望 psql 省略列标题等,所以我在 psql 命令行中添加了 -t -A 标志。

顺便说一句,我将from testdb.user 更改为FROM user,我认为您没有名为“testdb”的架构。

【讨论】:

    【解决方案2】:

    问题不止一个

    在 SQL 查询中改为引号,可以使用 $$

    postgres=# select interval $$90 min$$;
     interval 
    ──────────
     01:30:00
    (1 row)
    

    【讨论】:

    • 但我在 shell 脚本中运行我的查询,并将 echo 输出到文件中
    • 是的,我知道,您的问题在于嵌套引号使用不当。因此,使用 $$ 代替嵌套引号。 'SELECT .. 间隔'90 ...缺少'缺少第二个' .. ---> 'SELECT间隔$$90分钟$$'
    猜你喜欢
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    相关资源
    最近更新 更多