Difference between 2>&-, 2>/dev/null, |&, &>/dev/null and >/dev/null 2>&1
Just looking for the difference between
2>&-
2>/dev/null
|&
&>/dev/null
>/dev/null 2>&1
and their portability with non-Bourne shells
like tcsh
,
mksh
, etc.
For background:
- a number 1 = standard out (i.e. STDOUT)
- a number 2 = standard error (i.e. STDERR)
- if a number isn't explicitly given, then number 1 is assumed by the shell (bash)
First let's tackle the function of these. For reference see the Advanced Bash-Scripting Guide.
Functions
2>&-
The general form of this one is M>&-
, where "M" is a file descriptor number. This will close output for whichever file descriptor is referenced, i.e.
"M".
2>/dev/null
The general form of this one is M>/dev/null
, where "M" is a file descriptor number. This will redirect the file descriptor,
"M", to /dev/null
.
2>&1
The general form of this one is M>&N
, where "M" &
"N" are file descriptor numbers. It combines the output of file descriptors
"M" and "N" into a single stream.
|&
This is just an abbreviation for 2>&1 |
. It was added in Bash 4.
&>/dev/null
This is just an abbreviation for >/dev/null 2>&1
. It redirects file descriptor 2 (STDERR) and descriptor 1 (STDOUT) to
/dev/null
.
>/dev/null
This is just an abbreviation for 1>/dev/null
. It redirects file descriptor 1 (STDOUT) to
/dev/null
.
Portability to non-bash, tcsh, mksh, etc.
I've not dealt much with other shells outside of csh
and tcsh
. My experience with those 2 compared to bash's redirection operators, is that bash is superior in that regard. See the
tcsh man page for more details.
Of the commands you asked about none are directly supported by csh/tcsh. You'd have to use different syntaxes to construct similar functions.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通