如何在bash for循环中执行psql命令 [英] How to execute a psql command within a bash for loop
问题描述
我想在bash脚本中执行psql语句并将结果输出到文件.我下面的代码可以按需工作:
I want to execute a psql statement within a bash script and output the results to a file. The code I have below works as desired:
#!/bin/bash
query="select * from mytable;"
psql <<EOF > output.txt
\timing
$query
EOF
我想运行该psql命令块5次,并将结果附加到output.txt
.如果我再将其复制并粘贴4次,则效果很好,但是当我尝试将其放入for循环中时,会出现错误.有什么办法吗?
I want to run that psql command block 5 times and have the results appended to output.txt
. It works fine if I just copy and paste it an additional 4 times, but when I try to put it inside of a for-loop, I get errors. Is there any way to do this?
这是我累的循环:
#!/bin/bash
query="select * from mytable;"
for (( i=0; i<5; i++ ))
do
psql <<EOF > output.txt
\timing
$query
EOF
done
如果我将最后一个EOF
一直移到最左边,它只会执行一次,就好像循环不在那儿一样.
If I move the final EOF
all the way over to the left, it only executes once, as if the loop wasn't there.
推荐答案
每次在循环内使用>
覆盖文件.您需要在内部使用>>
或在循环外部使用>
:
You are overwriting the file each time with >
inside the loop. You need >>
inside or have >
outside the loop:
#!/bin/bash
query="select * from mytable;"
for (( i=0; i<5; i++ ))
do
psql <<EOF
\timing
$query
EOF
done > output.txt
在循环内将>
放入done
的效率要比>>
高一点.
Putting >
after done
is a little more efficient than >>
inside the loop.
类似的帖子:
这篇关于如何在bash for循环中执行psql命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!