envsubst 不能就地替换吗? [英] Can envsubst not do in-place substitution?

查看:44
本文介绍了envsubst 不能就地替换吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个配置文件,其中包含一些 ENV_VARIABLE 样式的变量.

I have a config file which contains some ENV_VARIABLE styled variables.

This is my file.
It might contain $EXAMPLES of text.

现在我希望将该变量替换为保存在我的实际环境变量中的值.所以我正在尝试这个:

Now I want that variable replaced with a value which is saved in my actual environment variables. So I'm trying this:

export EXAMPLES=lots
envsubst < file.txt > file.txt

但是当输入文件和输出文件相同的时候就不行了.结果是一个大小为 0 的空文件.

But it doesn't work when the input file and output file are identical. The result is an empty file of size 0.

这一定有充分的理由,一些我不知道的 bash 基础知识?如何实现我想做的事情,最好不要先输出到不同的文件,然后用它替换原始文件?

There must be a good reason for this, some bash basics that I'm not aware of? How do I achieve what I want to do, ideally without first outputting to a different file and then replacing the original file with it?

我知道我可以使用 sed 轻松做到这一点,但是当我发现 envsubst 命令时,我认为它应该非常适合我的用例,所以我'想用那个.

I know that I can do it easily enough with sed, but when I discovered the envsubst command I thought that it should be perfect for my use case, so I'd like to use that.

推荐答案

这是我使用的解决方案:

Here is the solution that I use:

originalfile="file.txt"
tmpfile=$(mktemp)
cp --attributes-only --preserve $originalfile $tmpfile
cat $originalfile | envsubst > $tmpfile && mv $tmpfile $originalfile

小心其他不使用临时文件的解决方案.管道是异步的,所以文件被截断后偶尔会被读取.

Be careful with other solutions that do not use a temporary file. Pipes are asynchronous, so the file will occasionally be read after it has already been truncated.

这篇关于envsubst 不能就地替换吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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