Cannot set global variable in piped bash function

Viewed 154

Normally you can set global variables inside bash functions.

But it seems not to be possible if the function is called by the pipe command. Is it possible to change this?

function myfunc()
{
    MYVAR=123
}

echo "hi" | myfunc
echo "MYVAR is $MYVAR" # $MYVAR  is not set. But why?
myfunc
echo "MYVAR is $MYVAR" # $MYVAR is now set as expected

Edit:

@Maroun wrote that piped functions are executed in a seperate process. But that cannot be as the following example shows:

#!/bin/bash
echo "main process is $$"

my_func ()
{
  echo "my_func is executed in process $$"
}

echo "hi" | my_func

Output:

main process is 3225
my_func is executed in process 3225

As you can see the process id is the same. Any ideas?

2 Answers

Check the documentation (Pipeline section):

Each command in a pipeline is executed as a separate process (i.e., in a subshell).

The variable MYVAR is not set since it's changed in a subshell that dies after the piped function has finished.

If you really want to use a pipe, instead of other alternatives for passing data, it is possible to use the lastpipe option, which makes the last command in a pipeline execute in the current environment.

#!/bin/bash

myfunc () {
    var=foo
}

shopt -s lastpipe

echo something | myfunc
echo "$var"

Running this script will print foo.

It only works if myfunc is last in the pipeline.

It also only works if job control is not active, so it won't work if you try to test it in an interactive shell. Run it as a script.

Related