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.

4

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I recommend using ${line%%:*} in case the line had more colons in it.
This one works perfect. I needed to use the double % as suggested by @PesaThe as I had a few more colons.
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" )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.