Parsing variables from config file in Bash Parsing variables from config file in Bash bash bash

Parsing variables from config file in Bash


Since your config file is a valid shell script, you can source it into your current shell:

. config_fileecho "Content of VARIABLE1 is $VARIABLE1"echo "Content of VARIABLE2 is $VARIABLE2"echo "Content of VARIABLE3 is $VARIABLE3"

Slightly DRYer, but trickier

. config_filefor var in VARIABLE1 VARIABLE2 VARIABLE3; do    echo "Content of $var is ${!var}"done


awk -F\= '{gsub(/"/,"",$2);print "Content of " $1 " is " $2}' <filename>

Just FYI, another pure bash solution

IFS="="while read -r name valuedoecho "Content of $name is ${value//\"/}"done < filename


If you need these...

Features

  • Single line and inline comments;
  • Trimming spaces around = (ie var = value will not fail);
  • Quoted string values;
  • Understanding of DOS line endings;
  • Keep safe, avoiding sourcing your config file.

Code

shopt -s extglobconfigfile="dos_or_unix" # set the actual path name of your (DOS or Unix) config filetr -d '\r' < $configfile > $configfile.unixwhile IFS='= ' read -r lhs rhsdo    if [[ ! $lhs =~ ^\ *# && -n $lhs ]]; then        rhs="${rhs%%\#*}"    # Del in line right comments        rhs="${rhs%%*( )}"   # Del trailing spaces        rhs="${rhs%\"*}"     # Del opening string quotes         rhs="${rhs#\"*}"     # Del closing string quotes         declare $lhs="$rhs"    fidone < $configfile.unix

Comments

tr -d '\r' ... deletes DOS carriage return.
! $lhs =~ ^\ *# skips single line comments and -n $lhs skips empty lines.
Deleting trailing spaces with ${rhs%%*( )} requires setting extended globbing with shopt -s extglob. (Apart using sed), you can avoid this, via the more complex:

rhs="${rhs%"${rhs##*[^ ]}"}"  

Test config file

## This is a comment var1=value1             # Right side comment var2 = value2           # Assignment with spaces ## You can use blank lines var3= Unquoted String   # Outer spaces trimmedvar4= "My name is "     # Quote to avoid trimming var5= "\"Bob\""         

Test code

echo "Content of var1 is $var1"echo "Content of var2 is $var2"echo "Content of var3 is [$var3]"echo "Content of var4 + var5 is: [$var4$var5]"

Results

Content of var1 is value1Content of var2 is value2Content of var3 is [Unquoted String]Content of var4 + var5 is: [My name is "Bob"]