Shell 脚本 2>&1 是咋回事?

I/O redirection

standard output

root@aliyun:~# cat foo
bar  # 标准输出流默认绑定的是显示器
root@aliyun:~# cat foo > output.txt  #把标准输出流重定向到 output.txt 这个文件,不在屏幕上显示。
root@aliyun:~# cat output.txt
bar

standard error

root@aliyun:~# cat nonexist.txt > output.txt
cat: nonexist.txt: No such file or directory  # nonexist.txt 这个文件不存在。这是标准错误信息。默认绑定的也是显示器。

file descriptor

In Unix and related computer operating systems, a file descriptor (FD, less frequently fildes) is an abstract indicator (handle) used to access a file or other input/output resource, such as a pipe or network socket.
简单来说 file descriptor 可以来访问 I/O 资源。就是一个数字。把每一个资源视为一个房间的话,那么 file descriptor 就是代表这个资源的房间号。拿着房间号就可以访问这个房间的资源。

standard Input stream

Standard input is a stream from which a program reads its input data.
The program requests data transfers by use of the read operation.
Not all programs require stream input.
For example, the dir and ls programs (which display file names contained in a directory) may take command-line arguments, but perform their operations without any stream data input.
Unless redirected, standard input is inherited from the parent process. In the case of an interactive shell, that is usually associated with thekeyboard.
不重定向,交互式的 Shell,标准输入流和键盘关联。标准输入流的这个 file descriptor(房间号) 是 0

standard output stream

Standard output is a stream to which a program writes its output data.
The program requests data transfer with the write operation.
Not all programs generate output.
For example, the file rename command (variously called mv, move, or ren) is silent on success.
Unless redirected, standard output is inherited from the parent process. In the case of an interactive shell, that is usually the text terminal which initiated the program.
不重定向,交互式 Shell, 标准输出流和终端关联。标准输出流的这个 file descriptor(房间号) 是 1

standard error stream

Standard error is another output streamtypically used by programs to output error messages or diagnostics. It is a stream independent of standard output and can be redirected separately.
标准错误流的这个 file descriptor(房间号) 是 2

重定向的语法

[FILE_DESCRIPTOR]>
注意 file_descriptor>要连着写。

输出流重定向

root@aliyun:~# cat foo 1> output.txt #1
root@aliyun:~# cat foo > output.txt  #2
# 可知 > 是 1> 简写形式。

错误流重定向

root@aliyun:~# cat nonexist.txt 2> output.txt

2>&1

use &1 to reference the value of the file descriptor 1 (stdout).
&1 表示引用标准输出流(fd = 1) 的值。

root@aliyun:~# cat foo > output.txt 2>&1
#  意思就是将标准错误流(fd = 2)重定向到和标准输出流(fd = 1)相同的位置(output.txt)。
root@aliyun:~#

References

1.理解 shell script idiom redirect
2. everything is a file descriptor
3. standard streams 标准流
4. I/O 重定向
5. software clobbering
6. file descriptor

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值