如何在不创建子shell的情况下将命令的输出存储在变量中[Bas​​h< v4] [英] How to store the output of command in a variable without creating a subshell [Bash <v4]

查看:47
本文介绍了如何在不创建子shell的情况下将命令的输出存储在变量中[Bas​​h< v4]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ksh 具有一个非常有趣的构造来执行此操作,此答案中对此进行了详细说明: https://stackoverflow.com/a/11172617/636849

ksh has a really interesting construct to do this, detailed in this answer: https://stackoverflow.com/a/11172617/636849

从Bash 4.0开始,有一个内置的 mapfile 内置命令可以解决此问题: http://www.gnu.org/software/bash/manual/html_node/Bash-Builtins.html

Since Bash 4.0, there is a builtin mapfile builtin command that should solve this problem: http://www.gnu.org/software/bash/manual/html_node/Bash-Builtins.html

但是奇怪的是,它似乎不适用于进程替换:

But strangely, it doesn't seem to work with process substitution:

foo () { echo ${BASH_SUBSHELL}; }
mapfile -t foo_output <(foo) # FAIL: hang forever here
subshell_depth=${foo_output[0]} # should be 0

但是如何在Bash v3.2中做到这一点?

But how to do this in Bash v3.2 ?

推荐答案

这是另一种方法,它与众不同,因此需要单独的答案.我认为该方法无Subshel​​l且无bash子进程:

Here's another way to do it, which is different enough that it warrants a separate answer. I think this method is subshell-free and bash sub-process free:

ubuntu@ubuntu:~$ bar () { echo "$BASH_SUBSHELL $BASHPID"; }
ubuntu@ubuntu:~$ bar
0 8215
ubuntu@ubuntu:~$ mkfifo /tmp/myfifo
ubuntu@ubuntu:~$ exec 3<> /tmp/myfifo
ubuntu@ubuntu:~$ unlink /tmp/myfifo
ubuntu@ubuntu:~$ bar 1>&3
ubuntu@ubuntu:~$ read -u3 a
ubuntu@ubuntu:~$ echo $a
0 8215
ubuntu@ubuntu:~$ exec 3>&-
ubuntu@ubuntu:~$

这里的窍门是使用 exec 在带有FD的读写模式下打开FIFO,这似乎具有使FIFO成为非阻塞状态的副作用.然后,您可以将命令重定向到FD,而不会阻止它,然后读取FD.

The trick here is to use exec to open the FIFO in read-write mode with an FD, which seems to have the side-effect of making the FIFO non-blocking. Then you can redirect your command to the FD without it blocking, then read the FD.

请注意,FIFO将是一个有限大小的缓冲区,可能在4K左右,因此,如果您的命令产生的输出超过此数量,它将最终再次阻塞.

Note that the FIFO will be a limited-size buffer, probably around 4K, so if your command produces more output than this, it will end up blocking again.

这篇关于如何在不创建子shell的情况下将命令的输出存储在变量中[Bas​​h&lt; v4]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆