Linux中的重定向命令使用教程详解

什么是重定向

我们在控制台输入命令,在屏幕上能看到正确的和错误的提示。如果我们想要改变这个输出到别的地方,就要用到重定向。我们用1表示正确的输出(也叫标准输出),默认不写,2表示错误输出。

图片[1]-Linux中的重定向命令使用教程详解-不念博客
重定向

‘>’

这个符号叫‘输出重定向’,单独用只记录正确的输出:

[root@localhost ~]# ls a ag > 1.txt
ls: 无法访问'ag': No such file or directory
[root@localhost ~]# cat 1.txt 
a

‘>’会覆盖原来的内容,比如我们用不同的内容重新输出到1.txt:

[root@localhost ~]# ls ca cd > 1.txt
[root@localhost ~]# cat 1.txt
ca
cd

‘>>’

追加重定向,它和‘>’的区别是,它不会覆盖重定向文本的内容,只会在文章末尾追加,我们还是以刚才的1.txt举例说明:

[root@localhost ~]# ls lesson >> 1.txt
[root@localhost ~]# ls lesson/
software_install
[root@localhost ~]# cat 1.txt 
ca
cd
software_install

‘2>’

错误输出重定向,只记录错误,会覆盖原内容。

[root@localhost ~]# ls cb cg 2> 2.txt
cb
[root@localhost ~]# cat 2.txt 
ls: 无法访问'cg': No such file or directory

‘2>>’

错误输出追加重定向,只记录错误,只追加写入。我们还是用2.txt做实验:

[root@localhost ~]# cat 2.txt 
ls: 无法访问'cg': No such file or directory
[root@localhost ~]# ls cb ck 2>> 2.txt
cb
[root@localhost ~]# cat 2.txt
ls: 无法访问'cg': No such file or directory
ls: 无法访问'ck': No such file or directory

‘&>’

正确、错误都输出到同一个文件:

[root@localhost ~]# ls
1.txt  a    abc  a_hard           ca  cd   gkl
2.txt  a9c  adc  anaconda-ks.cfg  cb  def  lesson
[root@localhost ~]# ls ca cb cm &> 3.txt
[root@localhost ~]# cat 3.txt
ls: 无法访问'cm': No such file or directory
ca
cb

‘&>>’就不单独举例了,我想大家都能猜出来是什么意思了。

正确和错误单独处理

例子:

[root@localhost ~]# ls ca cb cm > 4.txt 2>5.txt
[root@localhost ~]# cat 4.txt 
ca
cb
[root@localhost ~]# cat 5.txt
ls: 无法访问'cm': No such file or directory

正确和错误一起处理

两种办法。
1.> /dev/null 2>&1
这是我们最常见的,它叫将错误输出绑定到标准输出上。

[root@localhost ~]# ls 2 6
ls: 无法访问'6': No such file or directory
2
[root@localhost ~]# ls 2 6 >& aaa.txt
[root@localhost ~]# cat aaa.txt 
ls: 无法访问'6': No such file or directory
2

2.>&直接写在文件前面:

root@localhost ~]# ls 2 6 >& aaa.txt
[root@localhost ~]# cat aaa.txt 
ls: 无法访问'6': No such file or directory
2
© 版权声明
THE END
喜欢就支持一下吧
点赞144赞赏 分享
评论 抢沙发
头像
欢迎光临不念博客,留下您的想法和建议,祝您有愉快的一天~
提交
头像

昵称

取消
昵称代码图片

    暂无评论内容