Reputation: 83
I have a config file with the following content:
msgs.config:
tmsg:This is Title Message!
t1msg:This is T1Message.
t2msg:This is T2Message.
pmsg:This is personal Message!
I am writing a bash script that reads the msgs.config file variables and stores them into local variables. I will use these throughout the script. Due to permission I do not want to use the .
method (source).
tmsg
t1msg
t2msg
pmsg
Any help would be greatly appreciated.
Upvotes: 7
Views: 8574
Reputation: 532303
In case you change your mind about source
:
source <( sed 's/:\(.*\)/="\1"/' msgs.config )
This does not work if any of your values have double quotes.
Upvotes: 1
Reputation: 755026
You can use:
oldIFS="$IFS"
IFS=":"
while read name value
do
# Check value for sanity? Name too?
eval $name="$value"
done < $config_file
IFS="$oldIFS"
Alternatively, you can use an associative array:
declare -A keys
oldIFS="$IFS"
IFS=":"
while read name value
do
keys[$name]="$value"
done < $config_file
IFS="$oldIFS"
Now you can refer to ${keys[tmsg]}
etc to access the variables. Or, if the list of variables is fixed, you can map the values to variables:
tmsg="${keys[tmsg]}"
Upvotes: 8
Reputation: 7932
Read the file and store the values-
i=0
config_file="/path/to/msgs.config"
while read line
do
if [ ! -z "$line" ] #check if the line is not blank
then
key[i]=`echo $line|cut -d':' -f1` #will extract tmsg from 1st line and so on
val[i]=`echo $line|cut -d':' -f2` #will extract "This is Title Message!" from line 1 and so on
((i++))
fi
done < $config_file
Access the array variables as ${key[0]}
,${key[1]}
,.... and ${val[0]}
,${val[1]}
...
Upvotes: 1