当管道传递到函数时增加 bash 变量

发布于 2024-11-19 21:37:14 字数 469 浏览 3 评论 0原文

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

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”。
我看过此线程,但它不适用于我的情况- 当我尝试时,出现语法错误。

I'm trying to do the following:

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

But the increment doesn't work, the variable c stays '1'.
I've seen this thread, but it doesn't work for my case - when I try it, a syntax error appears.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

秋心╮凉 2024-11-26 21:37:15

链接问题中的技巧适用于我:

#!/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 扩展(例如 <( ))将不可用。

The trick in the linked question works for me:

#!/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")

this prints:

test#1
test again#2

Are you using #!/bin/bash as your shebang? If you use #!/bin/sh, some bash extensions (such as <( )) won't be available.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文