Last active
December 7, 2015 12:58
-
-
Save filviu/f42b6c956f84f83937a2 to your computer and use it in GitHub Desktop.
BASH config parser; reads three value pairs from .cfg file (I use it to store the target file as well so I can modifiy multiple configuration files) ignores whitespace and comments.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -o nounset # Treat unset variables as an error | |
shopt -s extglob | |
configfile="file.properties" | |
WEB_VARIABLE_FROM_PARRENT="www.example.com" | |
tr -d '\r' < $configfile | 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 | |
# echo the values read; | |
echo "[ $TARGETFILE ] -- [ $VARNAME ] -- [ $(eval echo "\"$VARVALUE\"") ]" | |
fi | |
done |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# comments work here | |
db.conf user=user | |
db.conf pass=password | |
db.conf database=db | |
# whitespace between lines works as well | |
web.conf path=/var/www | |
web.conf url=${WEB_VARIABLE_FROM_PARRENT} | |
# Having a proper EOL (or a comment on last line) is important |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment