首页 > shell中2>&1之类的命令中'&'是什么意思?

shell中2>&1之类的命令中'&'是什么意思?

鸟哥的书中详细讲了>,>>,2>,2>>这些东西,但唯独没讲&这符号是什么意思,只留了两句话让我猜测2>&1是将stderr合并到stdout,以及&>是stderr与stdout合并输出的意思.
尽管如此,我还是不懂&本身是什麽意思.网上搜到的回答也都是讲整个命令是什么意思,换个写法估计他们也不知道是什么意思,例如

3>&1 创建一个新的FD3,保存当前stdout的文件描述符
3>&- 关闭之前创建的FD3

所以我的问题是:&本身是什么意思?

还有一个小问题,因为普通用户使用find命令会同时有stdout和stderr,若想将它们都写入一个文件,正常命令是这样的

find /etc -name .bashrc > list 2>&1

我想问为什么不能调下顺序,比如这样

find /etc -name .bashrc 2>&1 > list

因为我觉得它们意思都是一样的,但结果不同难道仅是因为格式要求?


这里的&没有固定的意思

放在>后面的&,表示重定向的目标不是一个文件,而是一个文件描述符,内置的文件描述符如下

1 => stdout
2 => stderr
0 => stdin

换言之 2>1 代表将stderr重定向到当前路径下文件名为1regular file中,而2>&1代表将stderr重定向到文件描述符1的文件(即/dev/stdout)中,这个文件就是stdoutfile system中的映射

&>file是一种特殊的用法,也可以写成>&file,二者的意思完全相同,都等价于

>file 2>&1

此处&>或者>&视作整体,分开没有单独的含义

第二个问题:

find /etc -name .bashrc > list 2>&1
# 我想问为什么不能调下顺序,比如这样
find /etc -name .bashrc 2>&1 > list

这个是从左到右有顺序的

第一种

xxx > list 2>&1

先将要输出到stdout的内容重定向到文件,此时文件list就是这个程序的stdout,再将stderr重定向到stdout,也就是文件list

第二种

xxx 2>&1 > list

先将要输出到stderr的内容重定向到stdout,此时会产生一个stdout的拷贝,作为程序的stderr,而程序原本要输出到stdout的内容,依然是对接在stdout原身上的,因此第二步重定向stdout,对stdout的拷贝不产生任何影响

引自 http://www.gnu.org/software/bash/manual/bashref.html#Redirections

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.

【热门文章】
【热门文章】