代码之家  ›  专栏  ›  技术社区  ›  Thành Chung Bùi

如何在shellscript中执行psql时添加shell命令

  •  2
  • Thành Chung Bùi  · 技术社区  · 7 年前

    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

    有什么方法可以找回它吗?

    UNIX Co process

    1 回复  |  直到 7 年前
        1
  •  1
  •   Craig Ringer    7 年前

    psql 实际上没有任何流量控制,所以没有。你可以使用 \! 命令来运行shell,但由于您不能基于它做出流控制决策,因此它对您没有帮助。

    相反,反转控制。让您的shell脚本控制 psql 输出跑 psql -qAtX 所以只能得到元组输出。

    run it as a coprocess .我发现,到那时,从一种可以更好地集成查询的语言编写脚本变得更加有用,比如 python3 psycopg2