- 标准输出和重定向
- 一、文件描述符
- 二、重定向
- 1、==ls >file 或者 ls 1>file== :把结果保存到文件里面
- 2、ls 2>file (错的)
- 3、==lk 2>file==:把错误输出保存到文件里面
- 4、 ==lk 1> a.txt 2>&1== :实现标准输出或标准错误输出重定向到文件里面
- 5、==lk 1>> a.txt 2>&1==:追加重定向
- 6、==ls 1>>/dev/null 2>&1==:把输出信息重定向到无底洞
| 名称 | 文件描述符 |
|---|---|
| 标准输入 | 0 |
| 标准输出 | 1 |
| 标准输出错误 | 2 |
(1)注:标准输入一般指键盘输入,标准输出指控制台输出,标准错误输出也指控制台输出,输入用的少,主要是两个输出。
二、重定向简介:使用重定向可以把信息重定向到其他位置
1、ls >file 或者 ls 1>file :把结果保存到文件里面注:可以直接放一个空文件,不用新建文件夹
(1)ls >file举例:
[root@hadoop61 shellDemo]# more a.txt a.txt: 没有那个文件或目录 [root@hadoop61 shellDemo]# ls > a.txt [root@hadoop61 shellDemo]# more a.txt a.txt b.sh c.sh demo.sh d.sh for.sh if.sh nohup.out while2.sh while.sh
(2)ls 1>file举例:
```linux [root@hadoop61 shellDemo]# ls 1> a.txt [root@hadoop61 shellDemo]# more a.txt a.txt b.sh c.sh demo.sh d.sh for.sh if.sh nohup.out while2.sh while.sh
注:这个重定向每次都是覆盖,如果把信息重定向同一个文件,就会覆盖之前的信息
2、ls 2>file (错的)ls是标准输出,2是标准错误输出,所以ls2是获取不到内容的,空内容重写到a.txt还是空,ls就打印到控制台了
[root@hadoop61 shellDemo]# ls 2> a.txt a.txt b.sh c.sh demo.sh d.sh for.sh if.sh nohup.out while2.sh while.sh [root@hadoop61 shellDemo]# more a.txt [root@hadoop61 shellDemo]#3、lk 2>file:把错误输出保存到文件里面
注:
(1)lk是错误输出,如果要把lk重定向到文件是不行的
[root@hadoop61 shellDemo]# lk -bash: lk: 未找到命令 [root@hadoop61 shellDemo]# lk > a.txt -bash: lk: 未找到命令 [root@hadoop61 shellDemo]# more a.txt [root@hadoop61 shellDemo]#
(2)除非加个2
[root@hadoop61 shellDemo]# lk 2> a.txt [root@hadoop61 shellDemo]# more a.txt -bash: lk: 未找到命令 [root@hadoop61 shellDemo]#4、 lk 1> a.txt 2>&1 :实现标准输出或标准错误输出重定向到文件里面
简介:
(1)lk 1> a.txt 2>&1 :把标准输出 1重定向到文件 a.txt ,把标准错误输出 2 重定向到标准输出1里面,最终标准输出和标准错误都重定向到文件里面
注:
(1)重定向符号后面如果是一个文件或路径,直接写就行了,如果是文件描述符就要加&,不然会当成文件名。
举例:
[root@hadoop61 shellDemo]# lk 1> a.txt 2>&1 [root@hadoop61 shellDemo]# more a.txt -bash: lk: 未找到命令5、lk 1>> a.txt 2>&1:追加重定向
注:>>是追加,这个重定向是追加的意思,如果把信息重定向同一个文件,不会覆盖之前的信息,会把内容添加进去
[root@hadoop61 shellDemo]# lk 1> a.txt 2>&1 [root@hadoop61 shellDemo]# more a.txt -bash: lk: 未找到命令 [root@hadoop61 shellDemo]# lk 1>> a.txt 2>&1 [root@hadoop61 shellDemo]# more a.txt -bash: lk: 未找到命令 -bash: lk: 未找到命令 [root@hadoop61 shellDemo]# ls 1>> a.txt 2>&1 [root@hadoop61 shellDemo]# more a.txt -bash: lk: 未找到命令 -bash: lk: 未找到命令 a.txt b.sh c.sh demo.sh d.sh for.sh if.sh nohup.out while2.sh while.sh6、ls 1>>/dev/null 2>&1:把输出信息重定向到无底洞
(1)注:不想存的时候可以执行ls 1>>/dev/null 2>&1,扔黑洞里面,不会保存
(2)执行:
[root@hadoop61 shellDemo]# ls 1>>/dev/null 2>&1
(3)拓展:nohup command >/dev/null 2>&1 &
拓展解析:nohup command >/dev/null 2>&1 & 指将command保持在后台运行,并且将输出的日志忽略



