>& 、&> 、2>&1 、&> /dev/null……
学习 Linux 的过程中,可能会看到像 ls -ld /tmp /tnt >/dev/null 2>&1
这样的命令,面对>&12
这些符号,看上去就像一堆乱码,不知道是啥。
首先,0/1/2 这三个数字其实是文件描述符,对应于三个标准流:
整数值 | 名称 |
---|---|
0 | Standard input |
1 | Standard output |
2 | Standard error |
/dev/null(空设备) 是一个特殊的设备文件,它会丢弃一切写入其中的数据(但报告写入操作成功)。
>
是 重定向符号,可以将标准流重定向到用户指定的地方
& 用来干什么呢?
& is only interpreted to mean “file descriptor” in the context of redirections.
就是在重定向的场合,用以标识对应的文件描述符号。而如果不用&
,使用 2>1
,会创建一个文件 1
所以 >&
搭配来使用,重定向一个标准流到对应的文件描述符去。
>& is the syntax to redirect a stream to another file descriptor - 0 is stdin, 1 is stdout, and 2 is stderr.
command >file 2>&1
其实类似于指针
1,2,0 这些文件描述符只是引用,&1/&2/&0 是真正的设备
那么 command >file 2>&1 等于:
command 1>file 2>&1 等于
1 => file;&1 = file; 2 => file
而 command 2>&1 >file 等于
&1 = /dev/x; 2 => /dev/x; 1 => file
命令实践:
$ command &>file
说明:
This one-liner uses the &> operator to redirect both output streams - stdout and stderr - from command to file.
即 &>f 等于 把 1 和 2 的输出都指向 file
相当于:$ command >file 2>&1
测试过,使用 command 1>file 2>file,可能会有丢失问题(还不知道为什么)
使用场景:
输出只有1和2,就考虑什么情况下需要。如果需要保留正常输出信息和错误输出信息到文件,就用这个命令
变种:
$ command &>/dev/null
将输出(stdout,stderr)全部丢弃
相当于 $ command >/dev/null 2>&1
$ command 2>/dev/null
使用场景:譬如find权限不够,报很多错误信息,这时候就可以把这些错误信息丢掉
$ command >/dev/null
没有写文件描述符时,默认是用 1. 即等同于 command 1>/dev/null.
将 stdout 全部丢弃,留下 stderr 显示在屏幕上
更高级的简写
2>&1 |
可以简写为 |&
其实简单来说,要么分别操作1/2,要么一起操作1/2.
那么就好办了,就两个符号,&>
和 >
。主要记住&>
.(因为有个容易混淆的>&
)
&>
是把 1和2并起来(&),再一起重定向(>
)
>&
是将重定向(>
)到1或2(&
用来获取1或2对应的设备)
参考:
https://unix.stackexchange.com/questions/70963/difference-between-2-2-dev-null-dev-null-and-dev-null-21
https://stackoverflow.com/questions/818255/in-the-shell-what-does-21-mean