gpt4 book ai didi

bash - 无法在管道 bash 函数中设置全局变量

转载 作者:行者123 更新时间:2023-12-02 18:26:37 27 4
gpt4 key购买 nike

通常您可以在 bash 函数中设置全局变量。

但是如果函数是通过pipe命令调用的,好像就不行了。这有可能改变吗?

function myfunc()
{
MYVAR=123
}

echo "hi" | myfunc
echo "MYVAR is $MYVAR" # $MYVAR is not set. But why?
myfunc
echo "MYVAR is $MYVAR" # $MYVAR is now set as expected

编辑:

@Maroun 写道,管道函数在单独的进程中执行。但这不能如以下示例所示:

#!/bin/bash
echo "main process is $$"

my_func ()
{
echo "my_func is executed in process $$"
}

echo "hi" | my_func

输出:

main process is 3225
my_func is executed in process 3225

如您所见,进程 ID 相同。有什么想法吗?

最佳答案

检查 documentation (Pipeline section) :

Each command in a pipeline is executed as a separate process (i.e., in a subshell).

变量 MYVAR 未设置,因为它在管道函数完成后死亡的子 shell 中发生了更改。

关于bash - 无法在管道 bash 函数中设置全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70054538/

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