【问题标题】:How to read environment variable from the text file? [duplicate]如何从文本文件中读取环境变量? [复制]
【发布时间】:2021-06-28 03:53:28
【问题描述】:
  1. 大家好,我遇到了无法从文本文件中读取环境变量的问题。
  2. 这是文本文件的内容:

块引用

#INCLUDE
$ward/ancd/qwe
.........
.........

还有 bash 脚本

while IFS= read -r line
do
      echo "$line" # It shows $ward/ancd/qwe instead of tchung/folder/main/ancd/qwe
done < "$input"

块引用

echo时应该直接显示“tchung/folder/main/ancd/qwe”,但是输出的是$ward/ancd/qwe。 $ward 是一个环境变量,当直接回显时,它能够在 bash 中显示文件路径。但是在读取文本文件时,它无法真正识别环境变量。

块引用

我能想到的当前解决方案是将 $line 中匹配的 $ENVAR 替换为该值。

repo="\$ward" 
if echo "$line" | grep -q "$repo"
then
     # echo "match"
      line="${line/$repo/$ward}"
      #echo "Print the match line : $line"
fi

还有其他更灵活的方式可以在读取文件时识别环境变量而不用一一替换子串吗?

【问题讨论】:

    标签: bash shell scripting


    【解决方案1】:

    也许您需要评估回显中$line 的内容:

    while IFS= read -r line
    do
      echo $(eval "echo $line")
    done
    

    【讨论】:

      【解决方案2】:

      使用envsubst:

      envsubst "$input"
      

      【讨论】:

        猜你喜欢
        • 2017-03-06
        • 1970-01-01
        • 2011-09-11
        • 1970-01-01
        • 1970-01-01
        • 2021-03-12
        • 2021-12-21
        • 2021-06-13
        • 2010-12-30
        相关资源
        最近更新 更多