Linux系统配置及服务管理_第05章_重定向管道
Linux系统配置-重定向讲解
file descriptors ,FD,文件描述符
进程使用文件描述符来管理打开的文件
图示
FD是访问文件的标识,即链接文件
0是键盘只读
1,2是终端可以理解是屏幕
3+是文件,可读可写
示例
通过我们非常熟悉的VIM程序。来观察一个进程的FD信息。
1.通过一个终端,打开一个文本。
[[email protected] ~]# vim 1.txt
2.通过另一个终端,查询文本程序的进程号
[[email protected] ~]# ps axu |grep vim
3.在/proc目录中查看文本程序的FD
通常在 /proc/PID/fd 就能看到文件的FD调用情况。
[[email protected] ~]# ls -l /proc/3961/fd
lrwx------. 1 root root 64 7月 30 19:16 0 -> /dev/pts/0 //标准输入
lrwx------. 1 root root 64 7月 30 19:16 1 -> /dev/pts/0 //标准输出
lrwx------. 1 root root 64 7月 30 19:12 2 -> /dev/pts/0 //标准错误输出
lrwx------. 1 root root 64 7月 30 19:16 3 -> /root/.1.txt.swp //常规文件
4.总结
看到的0124就是FD,程序通过描述符访问文件,
可以是常规文件,也可以是设备文件。
2、重定向案例
输出重定向及综合案例
简介-输出重定向分为
(1)正确输出
1>等价于 > 覆盖
1>> 等价于>>追加
(2)错误输出
2>等价于 > 覆盖
2>> 等价于>>追加
案例1,输出重定向正确输出
[[email protected] ~]# date 1>1.txt//date时间内容写进1.txt中
[[email protected] ~]# date 1>>1.txt / /把时间内容追加到1.txt中
案例2:错误输出重定向
错误示范
[[email protected] ~]# ls /home/ 2> 1.txt
观察1.txt文件中没有内容,因为没有错误信息2> 只写错误的信息
正确示范
当某条命令产生错误时,才会有错误输出。
案例3: 正确和错误都输入到相同位置
[[email protected] ~]# ls /home//sfsfsf &>>1.txt
2.输入重定向及结合案例
简介:标准输入: < 等价 0<
案例:输入重定向发送邮件
1 观察默认发送邮件的过程
编写邮件
[[email protected] ~]# mail -s "111111" user01
66666
6666
123
. //结束符号
EOT
mail 电子邮件
-s 标题
111111 标题内容
user01 邮件接收人
点代表邮件编辑已结束。
查看邮件 切换到接受邮件账户user01
[[email protected] ~]# su - user01
查看邮件内容:[[email protected] ~]$ mail
按邮件编号:1.即可看邮件。
按q 退出。
2 使用重定向快速创建邮件
先准备一段邮件内容
[[email protected] ~]# vim ghr.txt
[[email protected] ~]# mail -s "dddd" < ghr.txt //利用输入重定向把文件内容代替人为的输入,快速创建邮件。
管道
1、管道 |
简介:
管道命令可以将多条命令组合起来,一次性完成复杂的处理任务。
语法:
command1 | command2 |command3 |…
指令1的标准输出
作为指令2的标准输入
案例
[[email protected] ~]# cat /etc/passwd | tail -3
[[email protected] ~]# ps aux | grep 'sshd'
tee管道
简介:
三通管道,即交给另一个程序处理。又保存一份副本
案例
[[email protected] ~]# cat /etc/passwd |tee 99.txt | tail -1 //tee 99.txt是查看passwd文件内容的同时把内容都写进99.txt中
tail -1 是显示内容的第一行
[[email protected] ~]# cat 99.txt
参数传递 Xargs
cp rm一些特殊命令就是不服其他程序。
案例;
1.环境准备,准备一些文件。
[[email protected] ~]# touch /home/file{1..5} // 同时创建五个文件
0
2 接到消息,部分文件需要删除。
[[email protected] ~]# vim files.txt
3 使用管道删除
[[email protected] ~]# cat files.txt |rm -rf
文件还在,删除失败了
4.貌似之前的不行。下面加上xargs
[[email protected] ~]# cat files.txt | xargs rm -rvf
已删除"/home/file1"
已删除"/home/file3"
已删除"/home/file5"
[[email protected] ~]# ls /home
通过|xargs成功连接rm命令
删除成功了