替换文件中的环境变量

时间:2021-05-11 03:47:51

标签: bash shell environment-variables zsh

我有一个 myfile 包含像

这样的行
#!/usr/bin/env python3
print("Hello world")
names = ('${(j:', ':)ZSH_VAR[@]}', )

我想用我加载的 shell 中的环境变量预处理这个文件(在我的例子中是 zsh,但通用的 bash 解决方案也可以很好地工作)。

我该怎么做

$ declare -ga ZSH_VAR=( 1 2 3 )
$ preprocess < myfile

这样输出是

#!/usr/bin/env python3
print("Hello world")
bar=('1', '2', '3', )

1 个答案:

答案 0 :(得分:2)

您可以为此使用 eval

$ BAR=1234 FOO=abcd; while read -r line; do eval 'echo "'"$line"'"'; done < "file"

或者在脚本中。 (script.sh)

#!/bin/bash

while read -r line; do eval 'echo "'"$line"'"'"; done < "file"

# If you want to redirect the output into a file (out.txt).
# while read -r line; do eval 'echo "'"$line"'" >> out.txt'; done < "file"
# Or  this
# while read -r line; do eval 'echo "'"$line"'"'; done < "file" > out.txt

然后像这样调用脚本:

FOO=abcd BAR=1234 ./script.sh 

注意

小心。确保您的文件不包含 rm 命令。只是为了安全。