I needed to write a Bash script that installs and provisions PostgreSQL for use with Rails 4.x. My project was using Vagrant so having a Bash script that provisioned each part of the project was important.

This is the installation that works for me.

#!/usr/bin/env bash
sudo apt-get update
sudo apt-get install -y postgresql \
                        postgresql-contrib \
                        libpq-dev

In my case I needed to enable Hstore. This script enables hstore if it isn’t already enabled.

#!/usr/bin/env bash
psql template1 -c "select 'a=>1'::hstore ? 'a'" >/dev/null 2>/dev/null
if [ $? == 1 ]; then
  psql template1 -c "create extension hstore;"
fi

I had some template issues related to the use of special Unicode characters which required making this change to the database template. I was storing the content of Twitter and Instagram posts which use emojis.

#!/usr/bin/env bash
echo 'export LANGUAGE="en_US.UTF-8"' >> /etc/profile.d/lang.sh
echo 'export LANG="en_US.UTF-8"' >> /etc/profile.d/lang.sh
export 'LC_ALL="en_US.UTF-8"' >> /etc/profile.d/lang.sh
psql -c "update pg_database set datistemplate=false where datname='template1'"
psql -c "drop database template1"
psql -c "create database template1 with owner=postgres encoding='UTF-8' lc_collate='en_US.utf8' lc_ctype='en_US.utf8' template template0"
psql -c "update pg_database set datistemplate=true where datname='template1'"

This code is now maintained in my install-stuff repository where I keep super simple Bash scripts that I use for provisioning Vagrant instances. Fork and Star on Github. Check there for the latest versions. I’d love to have some collaborators on that project.