gpt4 book ai didi

linux - 为什么在 $() 中使用管道时 bash 会执行我的脚本的 2 个实例

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:29:53 26 4
gpt4 key购买 nike

这是我的 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。在子 shell 中,bash 设置了管道,这就是为什么您会看到 findgrep 作为其子项的原因。

关于linux - 为什么在 $() 中使用管道时 bash 会执行我的脚本的 2 个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16072051/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com