How to execute a psql command within a bash for loop

前端 未结 2 974
Happy的楠姐
Happy的楠姐 2021-01-20 14:11

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         


        
2条回答
  •  无人共我
    2021-01-20 14:40

    It is usually better to not run Postgres in a loop. Just generate the commands you want to execute, then run the sequence of generated commands once.

    #!/bin/bash
    
    query="select * from mytable;"
    
    for (( i=0; i<5; i++ ))
    do
       cat <<___EOF
       \timing
       $query
    ___EOF
    done |
    psql > output.txt
    

    which of course in this case can be simplified to just

    #!/bin/bash
    printf '-- %s\n\\timing\nselect * from mytable;\n' {1..5} |
    psql >output.txt
    

    The brace expansion {1..5} is Bash-specific, so you can't use sh for this particular snippet. (There is a difference.)

提交回复
热议问题