Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 -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.

like image 228
Dor Avatar asked Apr 14 '26 15:04

Dor


1 Answers

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.

like image 66
Gordon Davisson Avatar answered Apr 16 '26 15:04

Gordon Davisson