0

I would like to redirect the output stream of a command to a function so I did this:

function aClassicCommand {

    sleep 1
    echo "this is logs"
}

##############################

function logsReceiver {

    read IN
    echo "received logs: $IN"
}

aClassicCommand | logsReceiver &

# doing stuff in parallel

wait

The problem is that the logsReceiver has no longer access to the external variables:

function aClassicCommand {

    sleep 1
    echo "this is logs"
}

##############################

var=0

function logsReceiver {

    read IN
    echo "received logs: $IN"

    # prints "in subshell var=0" and not "in subshell var=1"
    echo "in subshell var=$var"
}

aClassicCommand | logsReceiver &

var=1
echo "var=$var"

wait

The output is:

var=1
received logs: this is logs
in subshell var=0

but I want this:

var=1
received logs: this is logs
in subshell var=1

How can I solve it?
Thanks.

Cl00e9ment
  • 773
  • 1
  • 13
  • 30

1 Answers1

0

You have to export the variable:

export var=1
aClassicCommand | logsReceiver &

Set an environment variable. Mark each name to be passed to child processes in the environment.

If it's needed to pass data into an already running subshell, it's quite complicated problem and some sort of inter-process communication will be needed. See for example this question for details.

David Ferenczy Rogožan
  • 23,966
  • 9
  • 79
  • 68
  • I've tried it an it doesn't work. Maybe because `var=1` is located after the calling of `aClassicCommand` and not before. – Cl00e9ment Sep 20 '18 at 16:59
  • When a subshell is started, a new environment is created for it and environment variables are **copied** there so any changes made to the parent shell's environment after the subshell has been started are not reflected by the subshell obviously. You would probably need some interprocess communication but I have no clue if it's even possible in a shell. – David Ferenczy Rogožan Sep 20 '18 at 17:25
  • Check this question, maybe it will help you: https://unix.stackexchange.com/questions/132102/communication-between-multiple-processes – David Ferenczy Rogožan Sep 20 '18 at 17:33
  • 1
    This actually seems to be the procedure to follow. I was thinking that this is trivial problem but it isn't. So I revised my plan in order to not have this kind of problem to solve. Thanks a lot anyway for the time you spent to help me. – Cl00e9ment Sep 21 '18 at 13:50
  • OK, I have incorporated it into my answer. You're welcome. Glad you managed to solve your issue another way. – David Ferenczy Rogožan Sep 25 '18 at 10:21