gpt4 book ai didi

bash - while 循环返回一个额外的空行

转载 作者:行者123 更新时间:2023-11-29 14:35:41 27 4
gpt4 key购买 nike

我正在尝试编写一个 bash 脚本来列出我本地 postgres 数据库中的表

while read line
do
myarray+=("$line")
## debug
echo $line
done < <(psql -h ... -U ... -t -c "select distinct table_name from information_schema.columns where table_schema='myschema' ;")

我已经创建了 36 个表,但上面的代码输出了第 37 行完全空白的行。我检查了像这样的元素数量 echo ${#myarray[@]} ; 37 个元素。

如果我运行查询 select distinct table_name from information_schema.columns where table_schema='myschema' ;,我会返回 36 条记录。

我在 while 循环中使用进程替换方法,因为它看起来更快,但我认为错误来自那里。有什么想法吗?

最佳答案

在 Postgres 代码中,有 fputc('\n', fout); 添加为最后的无条件步骤,适用于所有输出格式,因此您需要将其过滤掉,例如:

while read line
do
myarray+=("$line")
## debug
echo $line
done < <(psql -h ... -U ... -t -c "select distinct table_name from information_schema.columns where table_schema='myschema' ;" \
| egrep -v "^$")

此外,请记住,如果将来您(或您的同事)将某些内容放入~/.psqlrc(例如,\timing on ) 它可能会破坏您的代码。为了防止它,使用 psql 的选项 --no-psqlrc(或 -X)。

关于bash - while 循环返回一个额外的空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45068168/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com