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

后端 未结 7 1174
长发绾君心
长发绾君心 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:23

    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)

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