如何在bash中将config ini文件转换为系统环境?

时间:2014-03-20 13:38:57

标签: bash

我有以下配置文件

# this is sample config file like config.ini
APP_HOME=/usr/local/bin
DATABASE_DIR=/usr/local/database

通常,为了作为系统环境进行访问,它应使用前面的export

# this is sample config file like config.rc
export APP_HOME=/usr/local/bin
export DATABASE_DIR=/usr/local/database

我可以

$ source config.rc
$ echo "APP_HOME is $APP_HOME"
APP_HOME is /usr/local/bin

现在哪一行命令将配置文件config.ini转换为系统环境最简单?可以与sed / awk命令结合使用

4 个答案:

答案 0 :(得分:8)

您可以告诉shell自动导出变量,如果您确实需要将其导出。

set -a               # turn on automatic export
source config.ini    # execute all commands in the file
set +a               # turn off automatic export

答案 1 :(得分:2)

sed 's/^/export /g' config.ini > config.sh && source config.sh

sed 命令将'export'添加到每行config.ini的开头,然后将输出重定向到config.sh,然后 source shell内置读取并在当前shell环境中执行导出。

答案 2 :(得分:0)

source if:

之后导出该文件中的变量
export $(grep -oP '^\s*\K[_[:alpha:]]\w+(?==)' config.ini)

答案 3 :(得分:-1)

一行:  cat 1.ini | awk '{print "export "$0}'