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

后端 未结 7 1173
长发绾君心
长发绾君心 2020-11-30 02:25

I have a file like

name1=value1
name2=value2

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

$name1=value1
$n         


        
相关标签:
7条回答
  • 2020-11-30 03:16

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

    source nameOfFileWithKeyValuePairs
    

    or

    . nameOfFileWithKeyValuePairs
    
    0 讨论(0)
  • 2020-11-30 03:16

    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"
    
    0 讨论(0)
  • 2020-11-30 03:18

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

    grep mykey $"/location/to/file" | awk -F= '{print $2}'
    
    0 讨论(0)
  • 2020-11-30 03:19

    Use:

    while read -r line; do declare  "$line"; done <file
    
    0 讨论(0)
  • 2020-11-30 03:19

    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"
    }
    
    0 讨论(0)
  • 2020-11-30 03:19

    sed 's/^/\$/' yourfilename

    0 讨论(0)
提交回复
热议问题