从键/值对文件设置环境变量 [英] Set environment variables from file of key/value pairs

查看:27
本文介绍了从键/值对文件设置环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TL;DR:如何将一组键/值对从文本文件导出到 shell 环境中?

TL;DR: How do I export a set of key/value pairs from a text file into the shell environment?

为了记录,以下是问题的原始版本,并附有示例.

For the record, below is the original version of the question, with examples.

我正在用 bash 编写一个脚本,它解析某个文件夹中包含 3 个变量的文件,这是其中之一:

I'm writing a script in bash which parses files with 3 variables in a certain folder, this is one of them:

MINIENTREGA_FECHALIMITE="2011-03-31"
MINIENTREGA_FICHEROS="informe.txt programa.c"
MINIENTREGA_DESTINO="./destino/entrega-prac1"

这个文件存放在./conf/prac1

This file is stored in ./conf/prac1

我的脚本 minientrega.sh 然后使用以下代码解析文件:

My script minientrega.sh then parses the file using this code:

cat ./conf/$1 | while read line; do
    export $line
done

但是当我在命令行中执行 minientrega.sh prac1 时,它没有设置环境变量

But when I execute minientrega.sh prac1 in the command line it doesn't set the environment variables

我也尝试过使用 source ./conf/$1 但同样的问题仍然存在

I also tried using source ./conf/$1 but the same problem still applies

也许还有其他方法可以做到这一点,我只需要使用我传递的文件的环境变量作为脚本的参数即可.

Maybe there is some other way to do this, I just need to use the environment variables of the file I pass as the argument of my script.

推荐答案

这可能会有所帮助:

export $(cat .env | xargs) && rails c

我使用它的原因是我想在我的 rails 控制台中测试 .env 的东西.

Reason why I use this is if I want to test .env stuff in my rails console.

gabrielf 想出了一种将变量保持在本地的好方法.这解决了从项目到项目的潜在问题.

gabrielf came up with a good way to keep the variables local. This solves the potential problem when going from project to project.

env $(cat .env | xargs) rails

我已经用 bash 3.2.51(1)-release

更新:

要忽略以 # 开头的行,请使用它(感谢 Pete 的评论):

To ignore lines that start with #, use this (thanks to Pete's comment):

export $(grep -v '^#' .env | xargs)

如果您想取消设置文件中定义的所有变量,请使用:

And if you want to unset all of the variables defined in the file, use this:

unset $(grep -v '^#' .env | sed -E 's/(.*)=.*/1/' | xargs)


更新:

要处理带有空格的值,请使用:

To also handle values with spaces, use:

export $(grep -v '^#' .env | xargs -d '
')

在 GNU 系统上 -- 或:

on GNU systems -- or:

export $(grep -v '^#' .env | xargs -0)

在 BSD 系统上.

来自这个答案,您可以通过以下方式自动检测操作系统:

From this answer you can auto-detect the OS with this:

export-env.sh

#!/bin/sh

## Usage:
##   . ./export-env.sh ; $COMMAND
##   . ./export-env.sh ; echo ${MINIENTREGA_FECHALIMITE}

unamestr=$(uname)
if [ "$unamestr" = 'Linux' ]; then

  export $(grep -v '^#' .env | xargs -d '
')

elif [ "$unamestr" = 'FreeBSD' ]; then

  export $(grep -v '^#' .env | xargs -0)

fi

这篇关于从键/值对文件设置环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆