In this quick article, we are presenting you with the shell script to start and stop PostgreSQL DB instance.
You can use these scripts as part of rc.d or init.dto be executed during the server shutdown and boot up.
Feel free to modify it further to suit your needs. Hope this helps.
Shell script to STOP PostgreSQL instance
You need to update a few key values on the script before executing.
- PATH - the path where the PostgreSQL binaries are present
- PGDATA - Data directory of your Postgres DB instance
- PG_LOG_FILE - log file location for this DB instance.
#!/usr/bin/env bash
# script to stop Postgres Database
export PATH=/cdwapps/local/pgsql/bin:$PATH
export PGDATA=/cdwsapps/airflow/database
PG_LOG_FILE=/cdwapps/airflow/logs/postgres.log
num_trys=0
while [[ ${num_trys} -lt 3 ]];do
if ! pg_ctl status; then
echo -e "postgre is running for PGDATA Location ${PGDATA} \n"
echo -e "Attempt: ${num_trys} to stop..."
pg_ctl stop -D ${PGDATA} -t 180
if [ $? -eq 0 ]
then
echo -e "Stop command Successful."
else
echo -e "Stop command Failed"
fi
echo -e "Waiting 30 seconds for DB Gracefully shutdown..."
sleep 30
if ! pg_ctl status; then
echo -e "PG ${PGDATA} has been stopped successfully..."
break
fi
((num_trys++))
else
break
fi
done
Shell script to start PostgreSQL instance
you need to update the following variables before using the script
- PATH - the path where the PostgreSQL binaries are present
- PGDATA - Data directory of your Postgres DB instance
- PG_LOG_FILE - log file location for this DB instance.
#!/usr/bin/env bash
export PATH=/usr/lib/postgresql/10/bin:$PATH
export PGDATA=/var/lib/postgresql/10/main
PG_LOG_FILE=/tmp/postgres.log
num_trys=0
while [[ ${num_trys} -lt 3 ]];do
if pg_ctl status; then
echo -e "postgre is running for PGDATA Location ${PGDATA} \n"
break
else
((num_trys++))
echo -e "Airflow PG ${PGDATA} not running \n"
echo -e "Attempt: ${num_trys} to restart..."
pg_ctl start -D ${PGDATA} -l ${PG_LOG_FILE}
echo -e "Waiting 30 seconds for DB to come up..."
sleep 30
if pg_ctl status; then
echo -e "PG ${PGDATA} has been started successfully..."
break
fi
fi
done
Are you in need of any Automation? you give us the challenge/problem statement we will solve it for you. reach out to us at [email protected]
Cheers
Sarav AK
Follow me on Linkedin My Profile Follow DevopsJunction onFacebook orTwitter For more practical videos and tutorials. Subscribe to our channel
Signup for Exclusive "Subscriber-only" Content






