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.
$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded. The grep manpage states: The exit status is 0 if selected lines are found, and 1 if not found.
Environment Variables Bash scripts can also be passed with the arguments in the form of environment variables. This can be done in either of the following ways: Specifying the variable value before the script execution command. Exporting the variable and then executing the script.
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.
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]}"
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]}
...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With