常用的文件描述符
/dev/stdin: 0
/dev/stdout: 1
/dev/stderr: 2
/dev/null: 黑洞
常用的操作
command > filename
# 重定向到某個文件, 如果文件已經(jīng)存在則刪除該文件,
# 文件不存在會新建, 因此命令成功與否原文件內(nèi)容都會丟失
command >> filename
# 同 > 相似, 只不過是追加到文件末尾
command 1> filename (簡寫為 >)
# stdout重定向
command 2> filename
# stderr重定向
M > N
# 重定向 M 到 N
# M 是一個文件描述符, 默認(rèn)為 1 (stdout)
# N 是一個文件描述符
M >& N
# M 合并到 N
# M 是一個文件描述符, 默認(rèn)為 1 (stdout)
# N 是一個文件描述符
M >& N (zsh下無效, 原因不明)
同
M &> N
# `>&` 或者 `&>` 是一個整體符號, 不要看成 `>` 和 `&`
常見用法
command > filename
等于
command 1> filename
# 重定向stdout覆蓋到filename
command >> filename
等于
command 1>> filename
# 重定向stdout追加到filename
commamd 2> filename
# 重定向stderr覆蓋到filename
command 2>> filename
# 重定向stderr追加到filename
command &> filename
# 重定向stdout和stderr覆蓋到filename
注意
如果一行命令stdout和stderr都不為空,
那么stderr的內(nèi)容在stdout的內(nèi)容的前面
ls > out.txt 2>&1 (1)
不等同于
ls 2>&1 >out.txt (2)
(1) stdout重定向到out.txt,然后stderr重定向到stdout(現(xiàn)在是out.txt)
(2)stderr重定向到stdout, 這時會產(chǎn)生一個stdout的拷貝,
作為程序的stderr, 然后原來的stdout重定向到out.txt,
拷貝的stdout沒有作用, 結(jié)果是stderr沒了, 原來的
stdout重定向到文件中去了
參考
http://www.runoob.com/linux/linux-shell-io-redirections.html
https://blog.csdn.net/win_turn/article/details/50379465
https://www.cnblogs.com/chengmo/archive/2010/10/20/1855805.html