我有以下职能。
hello () {
echo "Hello"
}
func () {
hello
echo "world"
}
如果我不想打印hello函数的输出,但想用它做些什么,我想在某个变量中捕获输出,唯一可能的方法是像下面这样派生一个subshell吗?这不是一个不必要的新子进程的创建吗?这可以优化吗?
func () {
local Var=$(hello)
echo "${Var/e/E} world"
}
7条答案
按热度按时间6rvt4ljy1#
一个丑陋的解决方案是临时替换
echo
,以便它设置一个全局变量,您可以从函数访问该变量:我承认这很讨厌,但避免了副壳。
5jvtdoz22#
使用文件描述符和Bash here字符串怎么样?
oxosxuxt3#
你可以让调用者传入一个变量名来保存输出值,然后在函数内部用这个变量名创建一个全局变量,如下所示:
那么就叫它:
因此,您的函数可以重写为:
唯一的限制是用于保存输出值的变量不能是局部变量。
相关的帖子,其中谈到使用nameref:
ds97pgxw4#
不是一个抨击的答案:至少有一个shell,ksh 优化命令替换
$( ... )
以 * 不 * 为内置命令产生子shell。当你的脚本倾向于执行很多这样的命令时,这会很有用。oogrdqng5#
你有修改
hello()
函数的选项吗?如果有,那么给予它一个选项,把结果存储在一个变量中:hello()
的一个更紧凑的版本:vu8f3i0k6#
这并不能从字面上回答这个问题,但对于某些用例来说,这是一种可行的替代方法...
这是@Andrew Vickers的衍生产品,因为你可以依靠
eval
。与其定义一个函数,不如定义一个我称之为“宏”的东西(C语言的等价物):
sg3maiej7#
1.将函数的stdout重定向到“自动”管道的写入端FD。然后,在(非分叉)调用之后,...
1.读取同一管道读取端的FD。
请注意,使用自动正常fd的代码将短得多,如下所示:
而不是像这段代码那样使用
create_pipe
函数(复制this answer)。但是这里使用的阅读FD行如下所示:将阻塞。并且有必要尝试使用如下超时进行阅读:
但是如果可能的话,我尽量避免任意的
sleeps
或timeouts
。\这里,关闭管道的写入端的FD会使读取的cat
行在内容的末尾返回(从我贫乏的知识中神奇地得出)。