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

为君一笑 提交于 2019-11-27 05:04:00
kurumi

Use:

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

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

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)

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"
Alex Stoliar

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!