`exec {logOutFd}>&1 {logErrFd}>&2` 这段代码是什么作用?

huangapple go评论66阅读模式
英文:

What does `exec {logOutFd}>&1 {logErrFd}>&2` do?

问题

我不理解这一行

exec {logOutFd}>&1 {logErrFd}>&2

这里没有变量引用,看起来只是一个空操作,就像没有参数运行exec一样。发生了什么?

英文:

I don't understand this line:

exec {logOutFd}>&1 {logErrFd}>&2

There are no variable dereferences, and it seems to be just a no-op, like running exec with no parameters. What's going on?

答案1

得分: 4

exec没有参数时用于启动持续到脚本结束的重定向。

根据Bash手册中的重定向部分:

> 每个可能由文件描述符号前导的重定向都可以由形式为*{varname}的单词前导。在这种情况下,对于除>&-<&-之外的每个重定向操作符,Shell将分配一个大于10的文件描述符号并将其分配给{varname}*。

因此,这将stdout和stderr复制到新的文件描述符,并分别将变量$logOutFd$logErrFd设置为这些描述符。

这允许稍后的代码在stdout或stderr被重定向的情况下写入原始的stdout或stderr,使用:

echo stdout message >&$logOutFd
英文:

exec with no parameters is used to start redirections that last for the rest of the script.

From the Bash manual section on redirection:

> Each redirection that may be preceded by a file descriptor number may instead be preceded by a word of the form {varname}. In this case, for each redirection operator except >&- and <&-, the shell will allocate a file descriptor greater than 10 and assign it to {varname}.

So this is duplicating stdout and stderr to new file descriptors, and setting the variables $logOutFd and $logErrFd to these descriptors, respectively.

This allows later code that executes while stdout or stderr are redirected to write to the original stdout or stderr, with

echo stdout message >&$logOutFd

答案2

得分: -1

Reviewing other preceding script: https://github.com/search?q=repo%3ANixOS%2Fnixpkgs%20%20logOutFd&type=code

`exec {logOutFd}>&1 {logErrFd}>&2` 这段代码是什么作用?

And reading:

They are using complex i/o redirections to return the stream pointer from some files previously open (8 and 9 position) to the classic stdout and stderr

exec 8>&1 9>&2
英文:

Reviewing other preceding script: https://github.com/search?q=repo%3ANixOS%2Fnixpkgs%20%20logOutFd&type=code

`exec {logOutFd}>&1 {logErrFd}>&2` 这段代码是什么作用?

And reading:

They are using complex i/o redirections to return the stream pointer from some files previously open (8 and 9 position) to the classic stdout and stderr

exec 8>&1 9>&2

huangapple
  • 本文由 发表于 2023年6月9日 07:32:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76436318.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定