0

Im preparing a shell script to generate analyze command and all the commands will go to a variable.

echo $analyze_query

analyze tbl1;
analyze tbl2;
analyze tbl3;

Now I want to run one by one, and Im able to achieve that by using the below command.

for $i in $analyze_query
do
psql -h host -U user -d db -c"$i"
done

But this query will close and open a new connection for every command, Is there any way that I can run the one by one but in one session?

1
  • You can use bash co-processes, but that is rather complicated (here is an example). I see no benefit in running those commands in a single transaction; why would you want to do that? Apr 14, 2020 at 6:41

1 Answer 1

1

Yes, we can do it.

  1. echo the variable and then pipe it to psql.

echo "$analyze_query" | psql -h host -U user -d db

  1. Use () to group the command output then pipe it to psql.

(for i in $analyze_query do echo $i done ) | psql -h host -U user -d db

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.