gpt4 book ai didi

bash - Shell 重定向 i/o 顺序

转载 作者:太空宇宙 更新时间:2023-11-04 11:59:45 24 4
gpt4 key购买 nike

我正在玩 i/o shell 重定向。我试过的命令(在 bash 中):

ls -al *.xyz 2>&1 1> files.lst

ls -al *.xyz 1> files.lst 2>&1

当前文件夹中没有任何*.xyz文件。

这些命令给我不同的结果。第一个命令在屏幕上显示错误消息 ls: *.xyz: No such file or directory。但是第二个将此错误消息打印到文件中。为什么第一个命令无法将错误输出写入文件?

最佳答案

Bash manual有一个明确的例子(类似于你的例子)来表明顺序很重要并解释了差异。这是摘录的相关部分(强调我的):

Note that the order of redirections is significant. For example, the command

ls > dirlist 2>&1

directs both standard output (file descriptor 1) and standard error (file descriptor 2) to the file dirlist, while the command

ls 2>&1 > dirlist

directs only the standard output to file dirlist, because the standard error was made a copy of the standard output before the standard output was redirected to dirlist.

This post从 POSIX 的角度解释它。

混淆是由于一个关键的区别而发生的。 > 重定向 不是 通过使左操作数 (stderr) 指向右操作数 (stdout) 但通过复制右操作数并将其分配给左侧。从概念上讲,是通过副本而不是通过引用进行赋值。

所以从左到右阅读,这是 Bash 解释的方式:ls > dirlist 2>&1 表示将 stdout 重定向到文件 dirlist ,然后将 stderr 重定向到当前的任何 stdout(这已经是文件 dirlist)。但是,ls 2>&1 > dirlist 会将 stderr 重定向到当前的任何 stdout(即屏幕/终端),然后重定向 stdoutdirlist

关于bash - Shell 重定向 i/o 顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52976400/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com