bash script 运行 psql 命令在后台的最佳实践是什么?

What is the best practice for a bash script running psql commands in the background?

我一直在测试产品的连接性和稳定性,我的部分测试是打开 8 个终端 windows,并启动一个使用 psql 查询远程数据库 10 次的脚本,每个查询抓取 50k 行。我给命令起了别名,因为我对它计时,将结果记录到另一个文件等。在这里我承认我不确定这是否是好的做法,我对 bash 配置文件和其他。 单击 8 个 windows(全部在一个更大的 window 中)变得非常烦人,所以我想我会尝试使用“ &" 在后台将其关闭 10 次。这已被证明是有问题的,并且远不如手动告诉 8 windows 启动脚本成功。主要是,window 我正在做“& & & & 等”的地方从来没有 "returns",我必须按 CTRL-C 才能返回提示。此外,我从 psql 得到了更多的服务器错误。这是我 运行 的两个命令,有些混淆和缩写:

test="(time bash ~/Documents/some/other/folders/myPsql.sh) >> \
~/Documents/some/stuff/logfile.txt 2>&1 && echo done"

shortcut="test & test & test & test & test & test & test & test & test & test"

这是 psql 脚本,当通过上面的 "test" 命令 运行 时,它工作正常:

psql << EOF
\pset pager off
\pset timing on
\copy (select * from sometable limit 50000) to '~/Documents/some/folder/file.csv' csv;
\q
EOF

我对这里工作的许多活动部件还很陌生,所以我认识到我正在做的事情可能在某些方面存在根本性缺陷。

是否有任何 "good"/更好的方法可以使我上面的 "shortcut" 命令更成功?

编辑:这是我指的错误:

psql: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request.

我在 Mac 上使用 iTerm2,psql 是 "talking to" 本地软件客户端,它与 Predix (CloudFoundry) 上的其他软件交互以查询也在 Predix 上的 Postgres 数据库.

test 是标准化的 shell 命令。用你自己的名字覆盖它会破坏很多 scripts/functions/etc.

psqlTest() {
  # DANGER: This filename can be used for SQL injection attacks. Keep it under control.
  local outFile=${1:-~/Documents/some/folder/file.csv}

  psql <<EOF
\pset pager off
\pset timing on
\copy (select * from sometable limit 50000) to '$outFile' csv;
\q
EOF
}

parallelPsqlTest() {
  local count=${1:-10}  # if not given a number, start 10 versions of our test
  for ((i=0; i<10; i++)); do
    psqlTest &
  done
}

一些注意事项:

  • 不要将命令存储在字符串中。参见 BashFAQ #50
  • ~ 对 shell 有意义,但 对大多数其他程序没有意义 。因此,您希望在 之前 将其扩展(替换为 /home/whatever/Users/whatever) shell 启动路径被传递到的任何软件。
  • 将变量替换为 SQL 文本是一个非常糟糕的主意。参见 Bobby Tables。即使对于文件名也是如此 - UNIX 上的文件名可以包含引号,可以包含换行符,并且可以包含一堆您可能认为它们不能包含的内容。
  • 不要将名称 test 用于您自己的命令:它是命令的正常名称,也称为 [,在 http://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html
  • 中指定
  • heredoc 中的反斜杠需要加倍以确保它们被传递给 psql 而不是被 shell 本身解释。