重定向
FD简介
file descriptors ,FD,文件描述符
进程使用文件描述符来管理打开的文件
FD是访问文件的标识,即链接文件
0是键盘只读,
1,2是终端可以理解是屏幕,
3+是文件,可读可写
示例
通过我们非常熟悉的VIM程序。来观察一个进程的FD信息。
1.通过一个终端,打开一个文本。
vim 1.txt
2.通过另一个终端,查询文本程序的进程号
ps aux| grep vim
3.在/proc目录中查看文本程序的FD
通常在 /proc/PID/fd 就能看到文件的FD调用情况。
[root@localhost ~]# ls /proc/5606/fd
感觉好像没什么。用用ls -l呢?
[root@localhost ~]# ll /proc/5606/fd
总用量 0
lrwx------. 1 root root 64 10月 10 07:37 0 -> /dev/pts/2
标准输入
lrwx------. 1 root root 64 10月 10 07:37 1 -> /dev/pts/2
标准输出
lrwx------. 1 root root 64 10月 10 07:37 2 -> /dev/pts/2
标准错误输出
lrwx------. 1 root root 64 10月 10 07:37 3 -> /root/.1.txt.swp
常规文件
4.总结
看到的0124就是FD,程序通过描述符访问文件,
可以是常规文件,也可以是设备文件。
标准输入、标准输出、标准错误
例1 标准输入输出
键盘0:标准输入 date < /file1.txt/程序<文件
文件输入到程序里ex:邮件 mail -s “sss” alice <word.txt
键盘1:标准输出
程序>文件
把程序输出到文件里,
案例2:错误输出重定向
错误示范
[root@lll ~]# ls /home/ 2> list.txt
观察list.txt文件中有没有内容?
因为没有错误信息
正确示范
当某条命令产生错误时,才会有错误输出。
[root@lll ~]# ls /aaaaaaaaa 2> list.txt
[root@lll ~]#cat list.txt
ls: 无法访问/aaaaaaaaa: 没有那个文件或目录
案例3: 正确和错误都输入到相同位置
[root@lll ~]# ls /home/ /aaaaaaaaa &>list.txt
生产环境
[root@lll ~]#yum install httpd &>/dev/null
2.输入重定向及结合案例
简介
标准输入: < 等价 0<
案例:输入重定向发送邮件
1 观察默认发送邮件的过程。
编写邮件
[root@lll ~]# mail -s "ssss" alice
111
222
333
.
点代表邮件编辑已结束。
查看邮件
[root@lll ~]# su - alice
[alice@lll ~]$ mail
Mail version 8.1 6/6/93. Type ? for help.
"/var/spool/mail/alice": 1 message 1 new
>N 1 root@lll.local Mon Oct 29 14:09 18/657 "ssss"
&
按邮件编号:1.即可看邮件。
按q 退出。
2 使用
重定向快速创建邮件
如果已经有了现成的邮件内容呢,如何快速输入邮件内容。
就可以用重定向创建邮件!!!
先准备一段邮件内容
vim word.txt
[root@lll ~]# mail -s "test01" alice < word.txt
原理:利用输入重定向,把文件内容代替人为的输入。
管道 |
进程管道 Piping
简介
管道命令可以将多条命令组合起来,一次性完成复杂的处理任务。
语法
command1 | command2 |command3 |...
tee管道
简介
三通管道,即交给另一个程序处理。又保存一份副本
案例
```python
[root@localhost ~]# cat /etc/passwd |tee 88.txt | tail -1
lll:x:1001:1001::/home/lll:/bin/bash
[root@localhost ~]# cat 888.txt
888.txt文本中是什么内容呢?一行还是所有行?
答案是 所有
目的是把输入保留副本,命令查询/tee文件/命令 文件保留查询内容
#### 参数传递 Xargs
cp rm一些特殊命令就是不服其他程序。
案例1
1 环境准备,准备一些文件。
```python
[root@localhost ~]# touch /home/file{1..5}
[root@localhost ~]#ls /home
2 接到消息,部分文件需要删除。
[root@localhost ~]# vim files.txt
/home/file1
/home/file3
/home/file5
3 使用管道
[root@localhost ~]# cat files.txt |rm -rvf
失败
4.貌似之前的不行。下面加上xargs
[root@localhost ~]# cat files.txt |xargs rm -rvf
removed ‘/home/file1’
removed ‘/home/file3’
removed ‘/home/file5’
[root@localhost ~]#ls /home
通过|xargs成功连接rm命令
cat files.txt |xargs rm -rvf
统计/usr/bin目录下的文件个数命令
ls /usr/bin/wc -l