A Script for Postgres Import and Export

jerry80409
2 min readOct 25, 2019

--

Photo by Volkan Olmez on Unsplash

I lost my self and fascinated with the SHELL scripts, so I twiddle my thumbs and write the script.

#!/usr/bin/env bash
#==============================
# An script help postgres database impoort and exoprt
#==============================

# an error occurred will stop script.
set -e

# an undefined parameter will throw error message.
set -u

# an pipeline failed will stop script.
set -o pipefail

#==============================
# Parameters
# You should change parameters for your Postgres connection.
#==============================
HOST='localhost'
DATABASE='database'
USER='database user'
PASSWD='database password'
TAR_FILE='tar file name'

#==============================
# Ansi colors
#==============================
RED='\033[0;31m'
BLUE='\033[0;34m'
YELLOW='\033[0;33m'
NCOLOR='\033[0m'

#==============================
# Message functions
#==============================
die() {
echo -e "${RED}ERROR:${NCOLOR} $1" 1>&2
exit 1
}

usage() {
echo -e "An script help postgres database impoort and exoprt"
echo -e "usage: `basename $0` [options]"
echo ""
echo -e "options:"
echo -e " ${YELLOW}-i${NCOLOR} import .tar file; usage: ${YELLOW}./`basename $0` -i${NCOLOR}"
echo -e " ${YELLOW}-o${NCOLOR} export to .tar; usage: ${YELLOW}./`basename $0` -o${NCOLOR}"
echo -e " ${YELLOW}-h${NCOLOR} help; usage: ${YELLOW}./`basename $0` -h${NCOLOR}"
echo ""
exit $1
}

confirm() {
local msg
if [[ -z $1 ]]; then
msg="Are you sure?"
else
msg=$1
fi

# call with a prompt string or use a default
read -r -p "${msg} [y/N/q] " response
case ${response} in
[yY][eE][sS]|[yY])
true
;;
[qQ][uU][iI][tT]|[qQ])
exit
;;
*)
false
;;
esac
}

import_data() {
local file=${TAR_FILE}
if [[ ! -f ${file} ]]; then
die "The file ${file} not existed."
fi

echo -e "${RED}This option will clean your database ${DATABSE}.${NCOLOR}"
if confirm ""; then
pg_restore -d${DATABASE} -U${USER} -c --if-exists -vvv -e ${file}
fi
}

export_data() {
local file=${TAR_FILE}
if [[ -f ${file} ]]; then
echo -e "rm -f ${file}"
rm -f ${file}
pg_dump -U${USER} -Ft ${DATABASE} -vvv > ${file}
fi
}

#==============================
# Handled user options
#==============================
while getopts "ioh?" opt; do
case "$opt" in
"i") import_data ;;
"o") export_data ;;
"h") usage 1;;
"?") usage 1;;
*) die "Unknown options.";;
esac
done

When you executed it, just like the figure.

--

--

jerry80409
jerry80409

Written by jerry80409

隨便記錄一些沒有整理很清楚的想法

No responses yet