开发者

increment bash variable when piping to function

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开发者_JAVA技巧 -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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜