gpt4 book ai didi

linux - 如何从后台进程 linux shell 脚本中获取结果?

转载 作者:太空狗 更新时间:2023-10-29 11:04:52 25 4
gpt4 key购买 nike

例如,假设我想计算 10 个大文件的行数并打印总数。

for f in files
do
#this creates a background process for each file
wc -l $f | awk '{print $1}' &
done

我正在尝试类似的事情:

for f in files
do
#this does not work :/
n=$( expr $(wc -l $f | awk '{print $1}') + $n ) &
done

echo $n

最佳答案

我终于找到了一个使用匿名管道和 bash 的可行解决方案:

#!/bin/bash

# this executes a separate shell and opens a new pipe, where the
# reading endpoint is fd 3 in our shell and the writing endpoint
# stdout of the other process. Note that you don't need the
# background operator (&) as exec starts a completely independent process.
exec 3< <(./a.sh 2&1)


# ... do other stuff


# write the contents of the pipe to a variable. If the other process
# hasn't already terminated, cat will block.
output=$(cat <&3)

关于linux - 如何从后台进程 linux shell 脚本中获取结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18138195/

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