Home > Back-end >  script to keep retrying a heredoc psql query until it succeeds with until loop
script to keep retrying a heredoc psql query until it succeeds with until loop

Time:09-16

I run a multi sql query transaction through psql manually as follows:

psql <<EOF
BEGIN;
Query1;
Query2;
COMMIT;
EOF

The issue here is that sometimes my transaction fails and need to keep retrying manually until success. This becomes a little tedious when it needs to repeatedly be done.

Is there a way to achieve this using until ?

My working attempt so far is:

until psql --file transaction.sql
do
    sleep 5
done

However, this requires an extra file outside the scope of this script.

is there a way to make it work in the following fashion:

# this is currently not working for me.
until psql <<EOF
   BEGIN;
   Query1;
   Query2;
   COMMIT;
EOF
do
    sleep 5
done

CodePudding user response:

You could try using a function.

#!/usr/bin/env bash

my_function(){
{
psql <<EOF
BEGIN;
Query1;
Query2;
COMMIT;
EOF
} && return 0
return 1
}

until my_function; do
  sleep 5
done
  • Related