[英]Why does bash execute 2 instances of my script when using a pipe inside of $()
这是我的bash脚本:
#!/bin/bash
$(find / -name "foo" | grep "bar")
ps的输出如下:
$ ps fx
PID TTY STAT TIME COMMAND
2690 ? Sl 1:04 gnome-terminal
5903 pts/8 Ss 0:00 \_ bash
7003 pts/8 S 0:00 \_ bash -x ./test_script.sh
7004 pts/8 S 0:00 | \_ bash -x ./test_script.sh
7005 pts/8 S 0:00 | \_ find / -name foo
7006 pts/8 S 0:00 | \_ grep bar
$ ps aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
1000 7003 0.0 0.0 5172 1108 pts/8 S 16:23 0:00 bash -x ./test_script.sh
1000 7004 0.0 0.0 5172 520 pts/8 S 16:23 0:00 bash -x ./test_script.sh
1000 7005 0.7 0.0 4720 1176 pts/8 S 16:23 0:00 find / -name foo
1000 7006 0.0 0.0 4368 824 pts/8 S 16:23 0:00 grep bar
如您所见,我的脚本有2个实例正在执行,谁能告诉我bash在这里到底在做什么? 具体来说,为什么要执行脚本的2个实例,并且有更好的方法呢?
谢谢
当您运行子shell( $(...)
部分)时,bash使用fork()
系统调用创建调用过程的副本(将在其中执行子shell命令)。 您的脚本不会再次运行,但是由于没有exec,因此命令行只是从父级继承而来。 bash在子外壳程序中设置了管道,这就是为什么您将find
和grep
视为其子级的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.