0

I'am trying to write a script that is waiting for a database to be online. The script that checks the database connection is written in python and should be excited every 5 seconds. If the script returns 0 the main script should continue.

I have never written in shell, so i can only guess how to get the python script into the condition of the while loop. Here is my attempt, but i have no idea how to get it right.

The python script is working well.

psqltest.py:

#!/usr/bin/python2.4
#
import psycopg2
try:
    db = psycopg2.connect("dbname='postgis' user='postgres' host='db' password='postgres'")
except:
    exit(1)

exit(0)

my main shell script:

echo waiting for database...
while  [ python /root/psqltest.py && echo 0 || echo 1 ]
  do
     sleep 5
  done

the error message:

 1 ]

Thanks for helping me out

4
  • OT, but do you have a good reason to be using python 2.4? Jul 25, 2016 at 12:58
  • not really, i think i can use python 3 as well
    – EidEchse
    Jul 25, 2016 at 13:00
  • Wouldn't it be easier to code the loop in Python and just have it return control to the shell script when there connection was successful?
    – DocZerø
    Jul 25, 2016 at 13:01
  • Please try shellcheck.net before asking humans to debug your code.
    – tripleee
    Jul 25, 2016 at 14:28

2 Answers 2

2

The shell script would simply be

while ! python /root/psqltest.py; do
    sleep 5
done

or the lesser known

until python /root/psqltest.py; do
    sleep 5
done
0

I have improved my Scripts, now the bash is only calling the python script and waits for it to finish, as Kristof mentioned. This is working so far, but i try to improve it further more.

#!/usr/bin/python3
#
import psycopg2
import time
import sys

db = None
sys.stdout.write('waiting ')
while db is None:
  try:
      db = psycopg2.connect("dbname='postgis' user='postgres' host='db' password='...'")
      db.close()
  except:
      sys.stdout.write('.')
  sys.stdout.flush()
  time.sleep( 5 )
print('')
exit(0)

Your Answer

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

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