Skip to content

Instantly share code, notes, and snippets.

@fernandes
Last active November 6, 2019 20:10
Show Gist options
  • Save fernandes/4549ca4c43a3721e4d2157e8a5ba3817 to your computer and use it in GitHub Desktop.
Save fernandes/4549ca4c43a3721e4d2157e8a5ba3817 to your computer and use it in GitHub Desktop.
Shell Script function to change postgresql values
# Error Codes
# 1: No variable name specified
# 2: No value found for variable
# If wanna save name = 'value' (between quotes), use: postgresql_config 12 foo \'bar\' (escaped)
postgresql_config() {
VERSION=$1
NAME=$2
VALUE=$3
MATCHED=0
set -x
[ -z $VERSION -o -z $NAME ] && echo "Use postgresql_config <cluster_version> <setting> <value>\nIf no value is passed, the current value will be returned"# && exit 1
CONFIG_FILE="/etc/postgresql/${VERSION}/main/postgresql.conf"
if [ -z $VALUE ]; then
value=`egrep -o "^${NAME} = [^[:space:]]+" ${CONFIG_FILE} |cut -d "=" -f2| sed -e 's/[[:space:]]*//'`
# if not found, return 2
[ -z $value ] && exit 2
# return the value found
echo $value
else
# check if variable exists
egrep -i "^#?${NAME} = " ${CONFIG_FILE} > /dev/null
# if exists
if [ $? -eq 0 ]; then
ESCAPED_VALUE=${VALUE//\//\\/}
# replace
# Matches name = ''
egrep -i "^#?${NAME} = ''" ${CONFIG_FILE} > /dev/null
if [ $? -eq 0 ]; then
MATCHED=1
POSTGRESQL_NEEDS_RELOAD=1
sed -i "s/^\(#\)\{0,1\}${NAME} = ''/${NAME} = '${ESCAPED_VALUE}'/g" ${CONFIG_FILE}
fi
# Matches name = 'value'
egrep -i "^#?${NAME} = '[^[:space:]]+'" ${CONFIG_FILE} > /dev/null
if [ $? -eq 0 -a $MATCHED -eq 0 ]; then
MATCHED=1
egrep -i "^${NAME} = '${VALUE}'" ${CONFIG_FILE} > /dev/null
if [ $? -ne 0 ]; then
sed -i "s/^\(#\)\{0,1\}${NAME} = '\([^[:space:]]\{0,\}\)'/${NAME} = '${ESCAPED_VALUE}'/g" ${CONFIG_FILE}
POSTGRESQL_NEEDS_RELOAD=1
fi
fi
# Matches name = value
egrep -i "^#?${NAME} = [^[:space:]^']+" ${CONFIG_FILE} > /dev/null
if [ $? -eq 0 -a $MATCHED -eq 0 ]; then
MATCHED=1
egrep -i "^${NAME} = ${VALUE}" ${CONFIG_FILE} > /dev/null
if [ $? -ne 0 ]; then
sed -i "s/^\(#\)\{0,1\}${NAME} = \([^[:space:]]\{0,\}\)/${NAME} = ${ESCAPED_VALUE}/g" ${CONFIG_FILE}
POSTGRESQL_NEEDS_RELOAD=1
fi
fi
else
# else append
echo "${NAME} = ${VALUE}" >> ${CONFIG_FILE}
fi
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment