# Look for ERROR string in both stdout and stderr.foo 2>&1 | grep ERROR
# Run the less pager without stderr screwing up the output.foo 2>&1 | less
# Send stdout/err to file (with append) and terminal.foo 2>&1 |tee /dev/tty >>outfile
# Send stderr to normal location and stdout to file.foo >outfile1 2>&1 >outfile2
$ ls -ld /tmp /tntls: cannot access /tnt: No such file or directorydrwxrwxrwt 118 root root 196608 Jan 7 11:49 /tmp
$ ls -ld /tmp /tnt >/dev/nullls: cannot access /tnt: No such file or directory
$ ls -ld /tmp /tnt 2>/dev/nulldrwxrwxrwt 118 root root 196608 Jan 7 11:49 /tmp
(当然,你没有一个名为/tnt的目录;)。好吧,我们有它!!
所以,让我们看看:
$ ls -ld /tmp /tnt >/dev/nullls: cannot access /tnt: No such file or directory
$ ls -ld /tmp /tnt >/dev/null 2>&1
$ ls -ld /tmp /tnt 2>&1 >/dev/nullls: cannot access /tnt: No such file or directory
最后一个命令行将STDERR转储到控制台,这似乎不是预期的行为……但是……
如果你想做一些关于标准输出的后过滤,错误输出或两者兼而有之:
$ ls -ld /tmp /tnt | sed 's/^.*$/<-- & --->/'ls: cannot access /tnt: No such file or directory<-- drwxrwxrwt 118 root root 196608 Jan 7 12:02 /tmp --->
$ ls -ld /tmp /tnt 2>&1 | sed 's/^.*$/<-- & --->/'<-- ls: cannot access /tnt: No such file or directory ---><-- drwxrwxrwt 118 root root 196608 Jan 7 12:02 /tmp --->
$ ls -ld /tmp /tnt >/dev/null | sed 's/^.*$/<-- & --->/'ls: cannot access /tnt: No such file or directory
$ ls -ld /tmp /tnt >/dev/null 2>&1 | sed 's/^.*$/<-- & --->/'
$ ls -ld /tmp /tnt 2>&1 >/dev/null | sed 's/^.*$/<-- & --->/'<-- ls: cannot access /tnt: No such file or directory --->
$ testfile=$(mktemp /tmp/testNoClobberDate-XXXXXX)
$ date > $testfile ; cat $testfileMon Jan 7 13:18:15 CET 2013
$ date > $testfile ; cat $testfileMon Jan 7 13:18:19 CET 2013
$ date > $testfile ; cat $testfileMon Jan 7 13:18:21 CET 2013
文件每次都被覆盖,现在好了:
$ set -o noclobber
$ date > $testfile ; cat $testfilebash: /tmp/testNoClobberDate-WW1xi9: cannot overwrite existing fileMon Jan 7 13:18:21 CET 2013
$ date > $testfile ; cat $testfilebash: /tmp/testNoClobberDate-WW1xi9: cannot overwrite existing fileMon Jan 7 13:18:21 CET 2013
通过>|:
$ date >| $testfile ; cat $testfileMon Jan 7 13:18:58 CET 2013
$ date >| $testfile ; cat $testfileMon Jan 7 13:19:01 CET 2013
取消设置此选项和/或查询是否已设置。
$ set -o | grep noclobbernoclobber on
$ set +o noclobber
$ set -o | grep noclobbernoclobber off
$ date > $testfile ; cat $testfileMon Jan 7 13:24:27 CET 2013
$ rm $testfile
4-最后一招和更多…
对于从给定命令重定向两者输出,我们看到正确的语法可能是:
$ ls -ld /tmp /tnt >/dev/null 2>&1
对于这种特别情况,有一个快捷语法:&>…或>&
$ ls -ld /tmp /tnt &>/dev/null
$ ls -ld /tmp /tnt >&/dev/null
注意:如果#0存在,#1也是正确的语法:
$ ls -ld /tmp /tnt 2>/dev/null 1>&2
4b现在,我让你想想:
$ ls -ld /tmp /tnt 2>&1 1>&2 | sed -e s/^/++/++/bin/ls: cannot access /tnt: No such file or directory++drwxrwxrwt 193 root root 196608 Feb 9 11:08 /tmp/
$ ls -ld /tmp /tnt 1>&2 2>&1 | sed -e s/^/++//bin/ls: cannot access /tnt: No such file or directorydrwxrwxrwt 193 root root 196608 Feb 9 11:08 /tmp/