gpt4 book ai didi

bash - 管道运行时增加 bash 变量

转载 作者:行者123 更新时间:2023-12-04 14:42:17 25 4
gpt4 key购买 nike

我正在尝试执行以下操作:

function func() # in practice: logs the output of a code block to a file
{
if [ -z "$c" ]; then
c=1
else
(( ++c ))
fi
tee -a /dev/null
echo "#$c"
}

{
echo -n "test"
} | func

{
echo -n "test"
} | func

但是增量不起作用,变量c保持'1'。
我看过this thread ,但它不适用于我的情况 - 当我尝试它时,会出现语法错误。

最佳答案

linked question 中的技巧对我有用:

#!/bin/bash
function func() # in practice: logs the output of a code block to a file
{
if [ -z "$c" ]; then
c=1
else
(( ++c ))
fi
tee -a /dev/null
echo "#$c"
}

func < <(echo -n "test")
func < <(echo -n "test again")

这打印:

test#1
test again#2

你在使用 #!/bin/bash作为你的 shebang?如果你使用 #!/bin/sh ,一些 bash 扩展(例如 <( ))将不可用。

关于bash - 管道运行时增加 bash 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6655323/

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