0 ——stdin 标准输入
1 ——stdout 标准输出
2 ——stderr 标准错误
将输出文本重定向或保存到一个文件:
$ echo "This is a sample test 1" > temp.txt
$ cat temp.txt
This is a sample test 1
$ echo "This is a sample test 2" >> temp.txt
$ cat temp.txt
This is a sample test 1
This is a sample test 2
$ echo "This is a sample test 2" > temp.txt
$ cat temp.txt
This is a sample test 2
注: “ > ” 会将etdout 输出到指定的文件中,但temp.txt中的内容首先会被清空。
“>>”将标准输出追加到目标文件中的尾部。
当使用重定向操作符时,输出内容不会在终端打印,而是被导向文件。
> = 1> ; >> == 1>>
/dev/null是一个特殊的设备文件,它接受到的任何数据都会被丢弃。null设备通常也被称为“黑洞”
$ ls + > out.txt
ls: cannot access +: No such file or directory
$ ls + 2> out.txt
$ cat out.txt
ls: cannot access +: No such file or directory
$ cmd 2>&1 output.txt -->等同于 cmd &> output.txt 将stderr转换成stdout,使得stderr和stdout都被重定向到同一个文件
bash: cmd: command not found...
Similar command is: 'mcd'
$ cat out.txt
ls: cannot access +: No such file or directory
$ cmd 2> /dev/null
$ cmd
bash: cmd: command not found...
Similar command is: 'mcd'
tee既可以将数据重定向到文件,还可以提供一份重定向数据的副本作为后续命令的stdin:
command |tee file1 file2
$ ls -tl
total 2
----------. 1 allen allen 47 Apr 27 01:07 out.txt
-rw-rw-r--. 1 allen allen 24 Apr 27 00:59 temp.txt
$ cat out.txt temp.txt
cat: out.txt: Permission denied
This is a sample test 2
$ cat out.txt temp.txt |tee a.txt |cat -n
cat: out.txt: Permission denied
1 This is a sample test 2
$ cat a.txt
This is a sample test 2
$
标准输出至a.txt,另外一份传递给 cat.
$ echo who is this |tee - "-"作为命令的文件名
who is this
who is this
补充:
借助重定向,我们可以用cat和管道|来指定我们自己的文件描述符:
$cat file |cmd
$cmd1 |cmd
将文件重定向到命令
$ cmd < file