我经常在网上看到用不同符号连接各种命令的教程。例如:
command1 | command2
command1 & command2
command1 || command2
command1 && command2
Run Code Online (Sandbox Code Playgroud)
其他人似乎将命令连接到文件:
command1 > file1
command1 >> file1
Run Code Online (Sandbox Code Playgroud)
这些是什么?他们叫什么?他们在做什么?还有更多吗?
只是寻找之间的区别
2>&-
2>/dev/null
|&
&>/dev/null
>/dev/null 2>&1
以及它们与非的Bourne shell喜欢便携性tcsh
,mksh
等等。
在这个 SO 线程和其他一些线程上,我看到了以下用于重定向stdout
和stderr
到文件的命令。
它们都是等价的吗?它们之间有什么区别吗?
command1 >> logfile 2>&1
command &> logfile
command >& logfile
Run Code Online (Sandbox Code Playgroud) 我运行以下命令:
pkg_add emacs-23.4,2.tbz 2> output.log
Run Code Online (Sandbox Code Playgroud)
输出仍然显示在终端中。当我按下时?,我得到
pkg_add emacs-23.4,2.tbz 2 > output.log
Run Code Online (Sandbox Code Playgroud)
前有一个空格2
。
我原来没有放这个。我试试
pkg_add emacs-23.4,2.tbz > output.log 2>&1
Run Code Online (Sandbox Code Playgroud)
同样,当我按下 时?,空格已添加。
为什么这会发生在我身上?
我在 FreeBSD 上运行 csh。
我在 tcsh 中遇到重定向问题。
考虑以下命令:vi --version
和vi --xxx
。让我们假设这是在vi
支持该--version
选项的机器上。该选项--xxx
无效,因此vim
应通过stderr
.
根据这个推理,2> /dev/null
与这两个命令一起使用应该给出有效情况的输出,而无效情况则没有输出。
这就是我在 bash、zsh、ksh 和 dash 中看到的。
$ vi --xxx 2> /dev/null
$ vi --version 2> /dev/null
VIM - Vi IMproved 7.4 (2013 Aug 10, compiled Oct 20 2014 16:09:17)
...
Run Code Online (Sandbox Code Playgroud)
但是,当我在 tcsh 中尝试此操作时,在这两种情况下都没有输出。
$ vi --xxx 2> /dev/null
$ vi --version 2> /dev/null
(there is no output here)
Run Code Online (Sandbox Code Playgroud)
这里发生了什么?我重定向stderr …
shell ×3
csh ×2
command-line ×1
control-flow ×1
freebsd ×1
portability ×1
stderr ×1
tcsh ×1
zsh ×1