bash 为什么用“envsubst <file >file”重写文件将其留空?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47081507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:34:23  来源:igfitidea点击:

Why does rewriting a file with "envsubst <file >file" leave it empty?

bashunixenvironment-variables

提问by Konstantin Shestakov

I need to put some environment variables values to file.

我需要将一些环境变量值放入文件。

cat file
# $VAR

echo $VAR
# text

When I do envsubst '$VAR $VAR' < file > filefile becomes empty. To resolve this issue I use envsubst '$VAR $VAR' < file | tee file 2>&1 >/dev/null. But sometimes it doesn't work, I mean file becomes empty. The first question is why sometimes file becomes empty and the second is what is the TRUE Unix way to put env vars to file in Linux and *BSD and MacOS ?

当我做envsubst '$VAR $VAR' < file > file文件变空。为了解决这个问题,我使用envsubst '$VAR $VAR' < file | tee file 2>&1 >/dev/null. 但有时它不起作用,我的意思是文件变空了。第一个问题是为什么有时文件变空,第二个问题是在 Linux 和 *BSD 和 MacOS 中将 env vars 放入文件的真正 Unix 方式是什么?

回答by chepner

The shell alwaysprocesses the output redirection, which truncates the file, before starting the command.

在启动命令之前,shell总是处理输出重定向,它会截断文件。

With the pipeline envsubst ... < file | tee file, the two commands envsubstand teerun asynchronously, which means the OS is free to start one or the other command first. You are basically tossing the dice that envsubstruns and reads filebefore teeruns and truncates the file.

与管道envsubst ... < file | tee file,两个命令envsubsttee运行异步的,这意味着所述OS是免费启动一个或另一个命令第一。您基本上envsubstfiletee运行和截断文件之前运行和读取的骰子。

The only correct solution is to write to a temporary file, then replace the original with the temporary file afteryou have confirmed that the command was successful.

唯一正确的解决方案是写入一个临时文件,然后确认命令成功用临时文件替换原来的文件。