Home > Software design >  Cannot set global variable in piped bash function
Cannot set global variable in piped bash function

Time:11-22

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

CodePudding user response:

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.

CodePudding user response:

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.

  •  Tags:  
  • bash
  • Related