本文共 2679 字,大约阅读时间需要 8 分钟。
今天和大家分享几个有趣的小知识,linux里重定向、管道和参数传递。
为什么说是有趣的呢,上课的时候这是我第一次上台 和大家做技术分享做的ppt的内容,然后有一天回头看的时候,有一些小想法,得到的结果却是出乎意料的,有点颠覆,具体会发在文末。
了解重定向首先要清楚几个概念:标准输入、标准输出、标准错误
文件描述符file descriptors 简称fd 或 Process I/O channels进程使用文件描述符来管理打开的文件[root@YourYG ~]# ls /proc/$$/fd0 1 2 255正确输出: 1> 1>> 等价于 > >>错误输出: 2> 2>>
案例1:输出重定向(覆盖)
[root@YourYG ~]# date 1> date.txt //date本来打印的是当前时间,我们用的这条命令是把本来输出的内容重定向到date.txt这个文件中[root@YourYG ~]# cat date.txtWed Dec 20 20:10:24 CST 2017案例2:输出重定向(追加)
[root@YourYG ~]# date >>date.txt[root@YourYG ~]# cat date.txtWed Dec 20 20:10:24 CST 2017Wed Dec 20 20:11:54 CST 2017案例3:错误输出重定向[root@YourYG ~]# ls dsadsadsadsadsadls: cannot access dsadsadsadsadsad: No such file or directory[root@YourYG ~]# ls dsadsadsadsadsad 2>test.txt[root@YourYG ~]# cat test.txtls: cannot access dsadsadsadsadsad: No such file or directory[root@YourYG ~]# 案例4:重定向到不同的位置[root@YourYG ~]# ls dsadsadsadsadsad >date.txt 2>test.txt //重定向到不同的位置注:>=1> 标准输出的1可省略
进程管道:把前面命令的结果交给后面的命令处理
用法:command1 | command2 |command3 |...案例1:查看所有进程,过滤出sshd的打印出来
[root@YourYG ~]# ps aux | grep 'sshd'root 1091 0.0 0.7 105480 3988 ? Ss 08:33 0:00 /usr/sbin/sshd -Droot 1195 0.0 1.0 147840 5256 ? Ss 08:34 0:01 sshd: root@pts/0root 25213 0.0 0.1 112652 924 pts/0 S+ 20:20 0:00 grep --color=auto sshd案例2:统计出最占CPU的5个进程[root@YourYG ~]# ps aux --sort=-%cpu |head -6USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMANDroot 1 0.0 0.7 125448 3896 ? Ss 08:33 0:07 /usr/lib/systemd/systemd --switched-root --system --deserialize 21root 2 0.0 0.0 0 0 ? S 08:33 0:00 [kthreadd]root 3 0.0 0.0 0 0 ? S 08:33 0:00 [ksoftirqd/0]root 6 0.0 0.0 0 0 ? S 08:33 0:00 [kworker/u2:0]root 7 0.0 0.0 0 0 ? S 08:33 0:00 [migration/0]
#cat a.txt
/passwd#cat a.txt | xargs -i cp {} /tmp#cat a.txt | xargs ls #cat a.txt | xargs -i ls {}通过xargs把管道前面的结果作为参数交给后面的命令> 案例[root@YourYG ~]# touch /home/file{1..5}[root@YourYG ~]# vim files.txt /home/file1/home/file2/home/file3/home/file4/home/file5[root@YourYG tmp]# cat files.txt |xargs ls -l-rw-r--r-- 1 root root 0 Dec 20 20:40 /home/file1-rw-r--r-- 1 root root 0 Dec 20 20:40 /home/file2-rw-r--r-- 1 root root 0 Dec 20 20:40 /home/file3-rw-r--r-- 1 root root 0 Dec 20 20:40 /home/file4-rw-r--r-- 1 root root 0 Dec 20 20:40 /home/file5[root@YourYG ~]# cat files.txt |xargs rm -rvf removed ‘/home/file1’removed ‘/home/file2’removed ‘/home/file4’removed ‘/home/file5’最后是我说的有趣的地方,大家先不要做,先看,然后思考会是什么结果,最后做做看和你想的是不是一样,为什么是这样?> [root@YourYG ~]# vim /a.txt> /etc/passwd> [root@YourYG ~]#cat /a.txt | ls> [root@YourYG ~]#cat /a.txt | cat> [root@YourYG ~]#cat /a.txt | echo
转载于:https://blog.51cto.com/13533802/2052666