shell重定向符

shell重定向符   >, < 及>>,<<

文件描述符   

0, 标准输入     对应文件/dev/stdin

1,标准输出     对应文件/dev/stdout

2,错误输出     对应文件/dev/stderr

&1,标准输出通道

&2,标准输入通道

command > file 是简写,原实际应为command 1>file;即把正确命令结果以标准输出方式写入file文件。

把错误输出重定向至标准输出,然后在重定向至he.txt文件

ubuntu@ubuntu-virtual-machine:~/work$ ls hello.txt he.txt> sc.txt 2>&1
ubuntu@ubuntu-virtual-machine:~/work$ cat sc.txt
ls: 无法访问 'he.txt': 没有那个文件或目录
hello.txt

把标准输出重定向至错误输出,由于错误输出未定向至文件,因此直接打印输出在显示器终端上,而不会写入sc.txt文件中
ubuntu@ubuntu-virtual-machine:~/work$ ls hello.txt he.txt> sc.txt 1>&2
ls: 无法访问 'he.txt': 没有那个文件或目录
hello.txt
ubuntu@ubuntu-virtual-machine:~/work$

其次重定向顺序很重要

ls hello.txt he.txt> sc.txt 2>&1

ubuntu@ubuntu-virtual-machine:~/work$ ls hello.txt he.txt> sc.txt 2>&1
ubuntu@ubuntu-virtual-machine:~/work$ cat sc.txt
ls: 无法访问 'he.txt': 没有那个文件或目录
hello.txt

上述命令是先把标准输出重定向至文件sc.txt. 然后把错误输出定向至标准输出(由于标准输出已定向至文件),因此该错误输出也一并写入文件sc.txt

ls hello.txt he.txt  2>&1   >sc.txt

buntu@ubuntu-virtual-machine:~/work$ ls hello.txt he.txt 2>&1 > sc.txt
ls: 无法访问 'he.txt': 没有那个文件或目录
ubuntu@ubuntu-virtual-machine:~/work$ cat sc.txt
hello.txt

上述命令是先把错误输出重定向至文件标准输出. 然后把标准输出定向至文件(由于标准输出未先定向至文件),因此该错误输出会直接通过已标准输出通道显示在屏幕上,最后标准输出写入文件sc.txt

/dev/null 这个设备,是linux 中黑洞设备,什么信息只要输出给这个设备,都会给吃掉

& 是一个描述符,如果1或2前不加&,会被当成一个普通文件。

1>&2 意思是把标准输出重定向到标准错误.

2>&1 意思是把标准错误输出重定向到标准输出。

&>filename 意思是把标准输出和标准错误输出都重定向到文件filename中

参考过

https://blog.csdn.net/dragon3100/article/details/100171995

https://www.cnblogs.com/f-ck-need-u/p/8727401.html

原文地址:https://www.cnblogs.com/yangjinhua/p/14634864.html