第四章:Linux重定向管道
重定向
文件句柄
linux万物皆文件,一个程序运行,依赖很多其他设备,比如打开一个文本,需要依赖键盘,显示器,鼠标等等,程序调用键盘,显示器这些方式就是通过FD,实际就是一个快捷方式,file description,文件句柄
[root@zhj ~]# ps aux | grep vim
root 33337 0.0 0.4 151788 8064 pts/0 S+ 11:42 0:00 vim file6
root 34061 0.0 0.1 112836 2376 pts/2 R+ 11:42 0:00 grep --color=auto vim
[root@zhj ~]# cd /proc/33337/fd
[root@zhj fd]# ll
总用量 0
lrwx------ 1 root root 64 4月 26 11:42 0 -> /dev/pts/0
lrwx------ 1 root root 64 4月 26 11:42 1 -> /dev/pts/0
lrwx------ 1 root root 64 4月 26 11:42 2 -> /dev/pts/0
lrwx------ 1 root root 64 4月 26 11:42 4 -> /root/.file6.swp
0:表示标准输入,键盘
1:表示标准输出,显示器
2:表示错误输出,显示器
输出重定向
一个>覆盖
二个>>追加
&>标准正确和标准错误都重定向
示列1:正确重定向效果展示
[root@zhj ~]# ls /root/ ljfalfafja/ 1> 1.txt
ls: 无法访问ljfalfafja/: 没有那个文件或目录
[root@zhj ~]# cat 1.txt
/root/:
1.txt
file100.txt
file1.txt
file2
file3.txt
file6
file66
test.txt
示列2:错误重定向展示
[root@zhj ~]# ls /root/ ljfalfafja/ 2> 1.txt
/root/:
1.txt file100.txt file1.txt file2 file3.txt file6 file66 test.txt
[root@zhj ~]# cat 1.txt
ls: 无法访问ljfalfafja/: 没有那个文件或目录
示列3:正确和错误重定向都不想要
[root@zhj ~]# ls /root/ ljfalfafja/ &> /dev/null
[root@zhj ~]# ls /root/ ljfalfafja/ &> /dev/null
[root@zhj ~]# ls /root/ ljfalfafja/ &> /dev/null
输入重定向
mail -s "test" alice < world.txt
管道
前一个命令的结果,作为后一个命令的输入
[root@zhj ~]# ps axu | grep mysql | wc -l
3
[root@zhj ~]# ps axu | grep mysql
mysql 3437 0.0 0.1 113424 3056 ? Ss 3月29 0:00 /bin/sh /usr/bin/mysqld_safe --basedir=/usr
mysql 3603 0.0 4.8 1119976 95556 ? Sl 3月29 10:30 /usr/libexec/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib64/mysql/plugin --log-error=/var/log/mariadb/mariadb.log --pid-file=/var/run/mariadb/mariadb.pid --socket=/var/lib/mysql/mysql.sock
root 15416 0.0 0.1 112836 2288 pts/0 R+ 15:11 0:00 grep --color=auto mysql
三通管道tee
[root@zhj ~]# ls /home
alice jack laozheng user01 user02 user100
[root@zhj ~]# ls /home | grep jack | wc -l
1
[root@zhj ~]# ls /home |tee /dev/pts/0 | grep jack | wc -l
alice
jack
laozheng
user01
user02
user100
1
[root@zhj ~]#
转义参数管道xargs
[root@zhj ~]# touch file{0..5}
[root@zhj ~]# ls
1.txt file0 file1 file2 file3 file4 file5 test.txt word.txt
[root@zhj ~]# vim test.txt
[root@zhj ~]# cat test.txt
/root/file1
/root/file2
/root/file3
/root/file4
/root/file5
[root@zhj ~]# cat test.txt | rm -rf
[root@zhj ~]# ls
1.txt file0 file1 file2 file3 file4 file5 test.txt word.txt
[root@zhj ~]# cat test.txt | xargs rm -rf #效果
[root@zhj ~]# ls
1.txt file0 test.txt word.txt
[root@zhj ~]#