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?
Solution 1:
If all lines in the input file are of this format, then simply sourcing it will set the variables:
source nameOfFileWithKeyValuePairs
or
. nameOfFileWithKeyValuePairs
Solution 2:
Use:
while read -r line; do declare "$line"; done <file
Solution 3:
Sourcing the file using .
or source
has the problem that you can also put commands in there that are executed. If the input is not absolutely trusted, that's a problem (hello rm -rf /
).
You can use read
to read key value pairs like this if there's only a limited known amount of keys:
read_properties()
{
file="$1"
while IFS="=" read -r key value; do
case "$key" in
"name1") name1="$value" ;;
"name2") name2="$value" ;;
esac
done < "$file"
}
Solution 4:
if your file location is /location/to/file
and the key is mykey
:
grep mykey $"/location/to/file" | awk -F= '{print $2}'
Solution 5:
suppose the name of your file is some.properties
#!/bin/sh
# Sample shell script to read and act on properties
# source the properties:
. some.properties
# Then reference then:
echo "name1 is $name1 and name2 is $name2"