bash “exec 3>&-”中的减号是什么意思,我该如何使用它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14066992/
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
What does minus mean in "exec 3>&-" and how do I use it?
提问by Redsandro
I often have trouble figuring out certain language constructs because they won't register when googling or duckduckgoing them. With a bit of experimenting, it's often simple to figure it out, but I don't get this one.
我经常无法弄清楚某些语言结构,因为它们在谷歌搜索或鸭鸭搜索时不会注册。通过一些实验,通常很容易弄清楚,但我不明白这个。
I often see stuff like 2>&1or 3>&-in bash scripts. I know this is some kind of redirection. 1 is stdout and 2 is stderror. 3 is probably custom. But what is the minus?
我经常看到类似bash 脚本2>&1或3>&-在 bash 脚本中的东西。我知道这是某种重定向。1 是标准输出,2 是标准错误。3 可能是自定义的。但减号是什么?
Also, I have a script whose output I want to log, but also want to see on screen. I use exec > >(tee $LOGFILE); exec 2>&1for that. It works. But sometimes when I bashtrap this script, I cannot type at the prompt anymore. Output is hidden after Ctrl+C. Can I use a custom channel and the minus sign to fix this, or is it unrelated?
另外,我有一个脚本,我想记录其输出,但也想在屏幕上看到。我用exec > >(tee $LOGFILE); exec 2>&1那个。有用。但有时当我 bashtrap 这个脚本时,我不能再在提示符下输入。输出在 之后隐藏Ctrl+C。我可以使用自定义渠道和减号来解决这个问题,还是不相关?
回答by banuj
2>&1means that stderr is redirected to stdout3>&-means that file descriptor 3, opened for writing(same as stdout), is closed.
2>&1意味着 stderr 被重定向到 stdout3>&-表示为写入而打开的文件描述符 3(与 stdout 相同)已关闭。
You can see more examples of redirection here
您可以在此处查看更多重定向示例
- As for questions number 3, I think thisis a good link.
- 至于第 3 个问题,我认为这是一个很好的链接。
回答by Sylvain Defresne
The 3>&-close the file descriptor number 3 (it probably has been opened before with 3>filename).
在3>&-关闭文件描述符3号(它可能已与前被打开3>filename)。
The 2>&1redirect the output of file descriptor 2 (stderr) to the same destination as file descriptor 1 (stdout). This dies call dup2()syscall.
该2>&1重定向文件描述符2(错误)的到同一目的地的输出作为文件描述符1(标准输出)。这死了调用dup2()系统调用。
For more information about redirecting file descriptor please consult the bash manpages (`man bash). They are dense but great.
有关重定向文件描述符的更多信息,请参阅 bash 联机帮助页 (`man bash)。它们很密集但很棒。
For your script, I would do it like that:
对于您的脚本,我会这样做:
#!/bin/bash
if [[ -z $recursive_call ]]; then
recursive_call=1
export recursive_call
"##代码##" "$@" | tee filename
exit
fi
# rest of the script goes there
It lose the exit code from the script though. There is a way in bash to get it I guess but I can't remember it now.
但是它丢失了脚本中的退出代码。我想在 bash 中有一种方法可以获得它,但我现在不记得了。

