8.5 输入输出重定向

时间:2022-04-27
本文章向大家介绍8.5 输入输出重定向,主要内容包括大于号,重定向、小于号,重定向、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

大于号,重定向

> 正确输出
>> 追加重定向
2> 错误重定向
2>> 错误追加重定向

>+2>等于&>        表示结合了正确和错误
  • cat 1.txt > 2.txt
    • 一个大于号表示正确的输出
    • 大于号>,表示前面的命令输出,直接输入到后面的文件中去
    • 就会把1.txt文件内容重定向到2.txt文件中,而2.txt之前的文件就会删除掉,重新写入1.txt文件内容
  • cat 1.txt >> 2.txt
    • 两个大于号>>,就是追加,不会删除2.txt文件内容,而是在原有的基础上将1.txt文件内容写入到2.txt文件中去
  • ls aaa.txt 2> err
    • 2大于号表示错误的输出(错误信息)
    • 2> 表示它会把命令产生的错误信息指定输入到一个文件中去
[root@hf-01 ~]# laaa
-bash: laaa: 未找到命令
[root@hf-01 ~]# laaa 2> a.txt
[root@hf-01 ~]# cat a.txt
-bash: laaa: 未找到命令
[root@hf-01 ~]# 
  • ls aaa.txt 2>> err
  • ls [12].txt aaa.txt &> a.txt //正确和错误的输出信息都输出到a.txt中
[root@hf-01 ~]# ls [12].txt aaa.txt &> a.txt
[root@hf-01 ~]# cat a.txt
ls: 无法访问aaa.txt: 没有那个文件或目录
1.txt
2.txt
[root@hf-01 ~]# 
  • 把正确和错误的输出到文件中,方法一 ls [12].txt aaa.txt &>> a.txt
[root@hf-01 ~]# ls [12].txt aaa.txt &>> a.txt
[root@hf-01 ~]# cat !$
cat a.txt
ls: 无法访问aaa.txt: 没有那个文件或目录
1.txt
2.txt
ls: 无法访问aaa.txt: 没有那个文件或目录
1.txt
2.txt
  • 把正确和错误的输出到文件中,方法二 ls [12].txt aaa.txt >1.txt 2>a.txt
[root@hf-01 ~]# ls [12].txt aaa.txt >1.txt 2>a.txt
[root@hf-01 ~]# cat 1.txt
1.txt
2.txt
[root@hf-01 ~]# cat a.txt
ls: 无法访问aaa.txt: 没有那个文件或目录
既可以写入一个文件中,也可以分开写入

小于号,重定向

  • 小于号< ,输入重定向
  • wc -l < 1.txt //把1.txt文件内容输入重定向到命令wc -l 中去
[root@hf-01 ~]# wc -l < 1.txt
2
[root@hf-01 ~]# 2.txt < 1.txt
-bash: 2.txt: 未找到命令
[root@hf-01 ~]# 
  • 输入重定向,左边必须是命令,不支持文件输入重定向到文件中的