Bash编程019——管道

Bash编程019——管道

之前在输入输出重定向中提到,每个进程默认都有三个对应的文件描述符(stdin、stdout、stderr),可以通过< >来重定向进程的文件描述符。如果要在进程间传递数据的话,使用输入输出重定向就比较麻烦了。比如:

ls / > ls.txt
grep bin < ls.txt
# 输出如下:
bin
sbin

匿名管道

管道(pipe)也可以看做是重定向的一种,它的作用是将一个进程的标准输出与另一个进程的标准输入相连接。

格式:command_1 | command_2 | command_3 | .... | command_N

# 对于上面的例子,使用管道
ls \ | grep bin
# 输出为:
bin
sbin

通过使用管道,我们可以轻松地将若干个命令组合起来使用。

示例:

# 统计根目录下的文件和目录的总个数
ls / | wc -l
# 输出为:26
ls /
# 输出如下
bin
boot
cdrom
dev
etc
home
initrd.img
initrd.img.old
lib
lib64
lost+found
media
mnt
opt
proc
root
run
sbin
snap
srv
sys
tmp
usr
var
vmlinuz
vmlinuz.old

注:wc命令可以用于统计文件的行数、单词数和字节数,具体使用方法见man wc。

再比如下面的例子:

head /proc/cpuinfo  | wc
10      41     209

ls -l /etc/ | tail
# 输出如下:
drwxr-xr-x  4 root root     4096 12月  7 21:23 vmware-tools
lrwxrwxrwx  1 root root       23 12月  7 21:10 vtrgb -> /etc/alternatives/vtrgb
-rw-r--r--  1 root root     4942 5月   9  2018 wgetrc
drwxr-xr-x  2 root root     4096 12月  7 21:19 wildmidi
-rw-r--r--  1 root root     1343 1月  10  2007 wodim.conf
drwxr-xr-x  2 root root     4096 12月  7 22:29 wpa_supplicant
drwxr-xr-x 10 root root     4096 12月  7 22:27 X11
drwxr-xr-x  5 root root     4096 12月  9 11:11 xdg
drwxr-xr-x  2 root root     4096 7月  31 08:37 xml
-rw-r--r--  1 root root      477 7月  20  2015 zsh_command_not_found

ls -l /etc | tail | sort
# 输出如下:
drwxr-xr-x 10 root root     4096 12月  7 22:27 X11
drwxr-xr-x  2 root root     4096 12月  7 21:19 wildmidi
drwxr-xr-x  2 root root     4096 12月  7 22:29 wpa_supplicant
drwxr-xr-x  2 root root     4096 7月  31 08:37 xml
drwxr-xr-x  4 root root     4096 12月  7 21:23 vmware-tools
drwxr-xr-x  5 root root     4096 12月  9 11:11 xdg
lrwxrwxrwx  1 root root       23 12月  7 21:10 vtrgb -> /etc/alternatives/vtrgb
-rw-r--r--  1 root root     1343 1月  10  2007 wodim.conf
-rw-r--r--  1 root root      477 7月  20  2015 zsh_command_not_found
-rw-r--r--  1 root root     4942 5月   9  2018 wgetrc

命名管道

上面使用的管道叫做匿名管道,还存在着另一种命名管道或者叫FIFO。命名管道是一种特殊类型的文件,主要用于进程间的通信。

示例:

# 标签页1
cd ~
mkfifo fifo
echo 1 > fifo # 此时进程会阻塞,再新打开一个标签页 ctrl+shfit+t

# 标签页2
cd ~
echo 2 > fifo # 再新打开一个标签页

# 标签页3
cat fifo 
# 输出如下,先入先出。
2
1

# 查看fifo
ls -l fifo
prw-rw-r-- 1 ruo ruo 0 1月  11 10:51 fifo

fifo文件类型为p即命名管道。

猜你喜欢

转载自blog.csdn.net/weixin_34044273/article/details/86821373