Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash script read file variables into local variables

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.

like image 482
thegreat078 Avatar asked Sep 05 '12 03:09

thegreat078


People also ask

What is $? == 0 in shell script?

$? 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.

How do I pass an environment variable in Bash script?

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.

What is $@ in Bash 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.


3 Answers

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]}"
like image 175
Jonathan Leffler Avatar answered Oct 20 '22 06:10

Jonathan Leffler


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]}...

like image 25
AnBisw Avatar answered Oct 20 '22 06:10

AnBisw


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.

like image 1
chepner Avatar answered Oct 20 '22 05:10

chepner