Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need bash shell script for reading name value pairs from a file

I have a file like

name1=value1 name2=value2 

I need to read this file using shell script and set variables

$name1=value1 $name2=value2 

Please provide a script that can do this.

I tried the first answer below, i.e. sourcing the properties file but I'm getting a problem if the value contains spaces. It gets interpreted as a new command after the space. How can I get it to work in the presence of spaces?

like image 592
Hugh Darling Avatar asked Feb 14 '11 09:02

Hugh Darling


People also ask

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.

What is $_ in shell script?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.


1 Answers

If all lines in the input file are of this format, then simply sourcing it will set the variables:

source nameOfFileWithKeyValuePairs 

or

. nameOfFileWithKeyValuePairs 
like image 120
Joachim Sauer Avatar answered Oct 04 '22 11:10

Joachim Sauer