'Need some clarity on shell-script for Docker setup on Phoeinx project
I found below shell-script(entrypoint.sh) from some GitHub Phoenix repo and I saw the same code in multiple Phoenix projects
#!/bin/bash
# Wait until postgres is ready
while ! pg_isready -q -h $PGHOST -p $PGPORT -U $PGUSER
do
echo "$(date) - waiting for database to start"
sleep 2
done
# Create migrate and seed database if it does't exist.
if [[ -z `psql -Atqc "\\list $PGDATABASE"` ]]; then
echo "Database $PGDATABASE does not exist. Creating..."
createdb -E UTF8 $PGDATABASE -l en_US.UTF-8 -T template0
mix ecto.migrate
mix run priv/repo/seeds.exs
echo "Database $PGDATABASE created."
fi
exec mix phx.server
the 1st block of code is clear it checks for Postgres readiness
but 2nd part I could not understand the if condition line if [[ -z
psql -Atqc "\list $PGDATABASE" ]];
and I searched postgres document some online resources but I couldn't find any reasonable explanation
and in my project I think that if fi
block of code not excuted, then I added 3 lines of code to make work
#!/bin/bash
# Docker entry point script.
# Wait until postgres is ready
while ! pg_isready -q -h $PGHOST -p $PGPORT -U $PGUSER
do
echo "$(date) - waiting for database to start"
sleep 2
done
# I added
echo "$(date) - PostgreSQL is ready"
mix ecto.create
mix ecto.migrate
# Create migrate and seed database if it does't exist.
if [[ -z `psql -Atqc "\\list $PGDATABASE"` ]]; then
echo "Database $PGDATABASE does not exist. Creating..."
createdb -E UTF8 $PGDATABASE -l en_US.UTF-8 -T template0
mix ecto.migrate
mix run priv/repo/seeds.exs
echo "Database $PGDATABASE created."
fi
exec mix phx.server
What is the explanation for this if [[ -z `psql -Atqc "\\list $PGDATABASE"` ]]; then
?
Solution 1:[1]
It runs the command psql -Atqc "\\list $PGDATABASE"
which tries to list a database with the name in the variable PGDATABASE. The -Atqc options remove all extra output, so if it's there, the only output will be the database name.
The -z
option on the if
statement checks if the length of a string is zero and returns true if it is.
So the result of the if
is that if the database doesn't exist, the code inside the if
is executed.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Hans Kilian |