如何从文本文件中读取环境变量?

问题描述

  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

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

解决方法

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

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

使用envsubst

envsubst "$input"