increment bash variable when piping to function

喜你入骨 提交于 2021-01-27 19:28:48

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/6655323/increment-bash-variable-when-piping-to-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!