Skip to content

Instantly share code, notes, and snippets.

@filviu
Created June 2, 2016 09:03
Show Gist options
  • Save filviu/ed878170fa65010281b308b676ac0b89 to your computer and use it in GitHub Desktop.
Save filviu/ed878170fa65010281b308b676ac0b89 to your computer and use it in GitHub Desktop.
Sniped used to edit configuration files using a template like file variable=value
#APPLICATION_ENV_SETTINGS is a file containing settings in format file variable=value
print_msg "Applying custom settings"
tr -d '\r' < "${APPLICATION_ENV_SETTINGS}" | while IFS='= ' read TARGETFILE VARNAME VARVALUE; do
# Don't declare variables here, you are in a sub-shell that dies
# when exitting while.
if [[ ! $TARGETFILE =~ ^\ *# && -n $TARGETFILE ]]; then
VARVALUE="${VARVALUE%%\#*}" # Del in line right comments
VARVALUE="${VARVALUE%%*( )}" # Del trailing spaces
VARVALUE="${VARVALUE%\"*}" # Del opening string quotes
VARVALUE="${VARVALUE#\"*}" # Del closing string quotes
# not uncomenting with sed because we may end with multiple variables (if first instance is commented and a second uncommented exits)
try_run "Setting $(basename ${TARGETFILE}): ${VARNAME}" sed -i "s|^[ ]*${VARNAME}[ ]*=.*|${VARNAME}=$(eval echo "\"$VARVALUE\"")|" "${APPLICATION_DIST_PATH}/${TARGETFILE}"
if ! grep -q "^[ ]*${VARNAME}[ ]*=.*" "${APPLICATION_DIST_PATH}/${TARGETFILE}" ; then
lastline=$(tail -n 1 "${APPLICATION_DIST_PATH}/${TARGETFILE}"; echo x); lastline=${lastline%x}
if [ "${lastline: -1}" != $'\n' ]; then
echo >> "${APPLICATION_DIST_PATH}/${TARGETFILE}"
fi
try_run " Actually had to add above at the end of file" echo
echo "# Automatically added" >> "${APPLICATION_DIST_PATH}/${TARGETFILE}"
echo "${VARNAME}=\"${VARVALUE}\"" >> "${APPLICATION_DIST_PATH}/${TARGETFILE}"
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment