【问题标题】:How to add shell commands while executing psql in shellscript如何在 shell 脚本中执行 psql 时添加 shell 命令
【发布时间】:2017-08-06 00:09:25
【问题描述】:

目前我正在编写一个在数据库上执行批处理作业的 shell 脚本,我想在执行 psql 时将 shell 脚本操作(如写入日志文件或回滚)放在某些条件下。 像这样

ConnectDb() {
	 PGPASSWORD=postgres psql -U postgres database -t -A -F , -v ON_ERROR_STOP=1 -v AUTOCOMMIT=0
}

printMsg() {
	echo "$PROGRAM/$SUBMODULE $(date "+ %Y%H%s")" $1 | tee -a ~/Desktop/shell/log/test.log
}

ConnectDb <<EOF
  start transaction;
  select * from ...;
  # do some database stubs here
  
  # i want to add somthing like this
  printMsg "Querying ..."
  # many shell script command go here
  if [ some accepted condition ] commit;
  if [ some bad conditions ] rollback;
  if [ should do more database query ] do insert, update, delete to database
  
  
  commit;
EOF

有什么方法可以找回吗?

更新 使用 coprocess 应该可以正常工作。 对于那些遇到同样问题的人 UNIX Co process

【问题讨论】:

    标签: shell psql coproc


    【解决方案1】:

    psql 并没有真正的流量控制,所以没有。您可以使用\! 命令运行shell,但由于您无法根据它做出流量控制决策,因此对您没有帮助。

    相反,反转控制。让您的 shell 脚本控制 psql 并根据 psql 输出做出决定。运行psql -qAtX,这样你只会得到元组输出。

    通常只运行psql 几次就足够了,但对于更复杂的情况,您可以run it as a coprocess。我发现到那时,从可以更好地集成查询的语言编写脚本开始变得更加有用,例如python3's psycopg2

    【讨论】:

    • coprocess 对我来说似乎是最好的选择,但是当我将连接更改为 coproc PGPASSWORD=postgres psql -U postgres database -t -A -F , -v ON_ERROR_STOP=1 -v AUTOCOMMIT=0 -q .当我运行 bash 时,终端说找不到 coproc,但如果直接在终端中运行,coproc 可以工作。我应该在这里做什么设置?
    • 谢谢,原因是我的 bash 版本不支持 coproc (v3.2),因为苹果没有更新 sh,所以使用 zsh 或 ksh 应该可以正常工作。十分感谢。它让我安全了一天
    猜你喜欢
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2013-09-22
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-04
    相关资源
    最近更新 更多