0

I've been looking through a lot of posts here but none of them can completely solve this out.

I've got a configuration file (ie: default.conf) with several values in it:

id: 2
type: food
name: potato
quantity: 34

What I would like to achieve is to have a bash script to read the config file and assign every single value after the ":" (2, food, potato, 34...) to multiple variables for posterior use in that script.

Ruben
  • 13
  • 3
  • Variables are meant to store singular strings. Store multiple strings in an array! – Inian Jul 12 '18 at 10:53
  • Sorry, I meant in multiple variables – Ruben Jul 12 '18 at 10:57
  • @ChandanKumar Use comments to ask for more information or suggest improvements. Avoid answering questions in comments. – John Kugelman Jul 12 '18 at 11:48
  • 1
    Possible duplicate of [Need bash shell script for reading name value pairs from a file](https://stackoverflow.com/q/4990575/608639) and [Code for parsing a key/value in in file from shell script](https://stackoverflow.com/q/15365871/608639) – jww Jul 12 '18 at 12:00

2 Answers2

1

I recommend using a associative array for this. This requires bash 4 or higher.

Loop over the file and use string manipulation from bash to assign the variables in your associative array.

declare -A conf_vars; while read line; do conf_vars[${line%:*}]=${line#*:}; done <default.conf

You can now use the variables by using e.g.: ${conf_vars[type]} which in your example gives food.

EDIT:
SO syntax coloring does not understand that in this case # does not indicate a comment. Just ignore it.

Hielke Walinga
  • 2,677
  • 1
  • 17
  • 30
0

Using read with : delimiter:

declare -A vars
while IFS=: read -r lvalue rvalue; do
    vars[$lvalue]=${rvalue# }
done < data

${rvalue# } removes the extra space. If the space is required, use just ${rvalue}.


Output:

declare -p vars
declare -A vars=([id]="2" [quantity]="34" [name]="potato" [type]="food" )
PesaThe
  • 7,259
  • 1
  • 19
  • 43