3

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.

Community
  • 1
  • 1
Dor
  • 7,344
  • 4
  • 32
  • 45

1 Answers1

3

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.

Community
  • 1
  • 1
Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151
  • What should I do if I need variable assignments in processes of both sides of a pipe? – Dor Jul 11 '11 at 19:57
  • Short answer: you can't, although there are other ways. Bash doesn't do multithreading, so each side of the pipe must run in a separate process, and separate processes can't set each others' shell variables. A couple of workarounds: First, rather than using a pipe, you could run one function with output redirected to a temporary file; then run the other with input redirected from the file. Second, let one of the functions run as a subshell, and have it store the relevant value(s) into a temp file; then read that and assign it to variables in the main shell. – Gordon Davisson Jul 11 '11 at 20:14