gpt4 book ai didi

linux - Bash管道消费顺序

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:24:35 25 4
gpt4 key购买 nike

假设我编写了几个 Bash 脚本,它们旨在与类似的管道一起使用以便于组合:

$ ./foo.sh /tmp/{one,two} | ... <potentially more pipes here, e.g. grep> ... | ./bar.sh

哪里foo.sh

  1. mkdir文件夹 /tmp/one/tmp/two , 和
  2. echo每个创建的文件夹路径作为标准输出的新行

bar.sh应该是

  1. 获取其 STDIN 的每一行(例如 $folder)
  2. sleep 2秒,模拟小延时
  3. 触摸 $folder/bar.txt 中的文件

tl;dr:我的 foo.sh stdout 生产几乎总是超过 bar.sh 的消费率.

问题是,我不想要我的 mkdir /tmp/two命令 foo.sh直到我的bar.sh发生完成使用对应于 mkdir /tmp/one 的标准输入 echo 输出。换句话说,我希望发生的事情的顺序应该是这样的:

  1. foo.sh : mkdir /tmp/one
  2. bar.sh : touch /tmp/one/bar.txt ( sleep )
  3. foo.sh : mkdir /tmp/two
  4. bar.sh : touch /tmp/two/bar.txt ( sleep )

我知道 Bash pipe 可能不是解决这里问题的方法。我的问题是,这仍然可以以某种方式实现吗?随意添加获得正确排序所需的任何额外管道或命令的使用(想到 xargs)。

最佳答案

假设 foo.sh 知道 bar.sh 在做什么,它可以简单地监视适当的文件:

mkdir /tmp/one
# Polling isn't great, but can be replaced with OS-specific tools
# like inotify
until [[ -f /tmp/one/bar.txt ]]; do
sleep 1
done
mkdir /tmp/two
# etc

这不需要 bar.sh 有任何关于 foo.sh 的特殊知识。或者,您反转谁知道谁,并让 foo.sh 简单地阻塞固定资源:

mkdir /tmp/one
touch /tmp/barrier
while [[ -f /tmp/barrier ]]; do
sleep 1
done
mkdir /tmp/two

现在 bar.sh 有责任了解 /tmp/barrier 并在创建 /tmp/one/bar.txt 后删除它

无论哪种方式,一个人都需要了解另一个人才能知道如何发送信号。

关于linux - Bash管道消费顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37445807/

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