linux - 导出带有特殊字符的 .env

标签 linux bash environment-variables

我正在使用 set -o allexport;来源.env;设置 +o allexport 以从 .env 文件中导出所有变量。不幸的是,一个变量包含 ),因此它会导致语法错误。上面的命令有解决办法吗?我知道可以将它设置在括号中,但是 .env 是在某种程度上自动生成的,没有括号。

例如,Dotenv 看起来像这样:

username=test
password=*fdas_dfar+)mbn

最佳答案

source .env

source 是一个 shell 命令,.env 文件被解析为 shell 文件。您需要引用您的字符串,就像在 shell 中一样。

username=test
password='*fdas_dfar+)mbn'

它的优点是,您可以从该文件运行所有 shell 命令:

username=$(echo test)
password='*fdas_dfar+)mbn'

或者您可以编写自己的解析器,例如:

while IFS='=' read -r name value; do
       if [ -z "$value" -o -z "$name" ]; then
           echo "Error - unparsable line!" >&2
           exit 1
       fi

       # add quotes around `'`
       value=$(<<<"$value" sed "s/'/'\''/g")
       
       # set the variable value using bash special builtin
       printf -v "$name" "%s" "$value"

 done <.env

关于linux - 导出带有特殊字符的 .env,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55703950/

相关文章:

bash - 为什么 influxdb 无法启动?

linux - 结合 grep sed 和 while

C++ IDE 在特定命名空间内搜索

c# - Linux 开发中的资源权限

bash - 如何在非 Bash Shell 中迭代 Null 分隔结果

azure - 如何在 SPA Nuxt Web 应用程序中访问客户端的 Azure 应用程序设置

java - 在Java中保存环境变量

ruby-on-rails - Rails 应用程序不读取 .bashrc 中的环境变量

c++ over linux gcc 继承

linux - 在 Debian Wheezy 上编译内核