7

I have a text configuration file something like this :

## COMMENT
KEY1=VALUE1  ## COMMENT
KEY2=VALUE2

KEY3=VALUE3  ## COMMENT

## COMMENT

As you can see, this has key value pairs, however it also contains comment lines and blank lines. In some cases, the comments are on the same line as the key value pair.

How do I read this config file and set the keys as variable names in a shell script so that I can use them as :

echo $KEY1 
4

3 回答 3

11

只是:

source config.file

那么你可以在你的shell中使用这些变量。

于 2013-09-13T15:25:45.397 回答
7

例如,这是您的配置文件的内容:

email=test@test.com
user=test
password=test

有两种方法:

  1. 使用源来做到这一点。

    source $<your_file_path>
    echo $email
    
  2. 读取内容,然后循环每一行进行比较以确定正确的行

    cat $<your_file_path> | while read line
    do 
      if [[$line == *"email"*]]; then
        IFS='-' read -a myarray <<< "$line"
        email=${myarray[1]}
        echo $email
      fi
    done
    

第二种解决方案的缺点是您需要使用 if 来检查每一行。

于 2016-03-08T20:14:21.223 回答
3

只需在代码开头获取代码:

. file

或者

source file
于 2013-09-13T15:24:41.843 回答