Question

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?

Was it helpful?

Solution

Use:

while read -r line; do declare  "$line"; done <file

OTHER TIPS

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

source nameOfFileWithKeyValuePairs

or

. nameOfFileWithKeyValuePairs

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"
}

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"

Improved version of @robinst

read_properties()
{
  file="$1"
  while IFS="=" read -r key value; do
    case "$key" in
      '#'*) ;;
      *)
        eval "$key=\"$value\""
    esac
  done < "$file"
}

Changes:

  • Dynamic key mapping instead of static
  • Supports (skips) comment lines

A nice one is also the solution of @kurumi, but it isn't supported in busybox

And here a completely different variant:

eval "`sed -r -e "s/'/'\\"'\\"'/g" -e "s/^(.+)=(.+)\$/\1='\2'/" $filename`"

(i tried to do best with escaping, but I'm not sure if that's enough)

if your file location is /location/to/file and the key is mykey:

grep mykey $"/location/to/file" | awk -F= '{print $2}'

sed 's/^/\$/' yourfilename

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top