LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Piping the output of a function (https://www.linuxquestions.org/questions/linux-newbie-8/piping-the-output-of-a-function-923910/)

akhand jyoti 01-15-2012 12:41 PM

Piping the output of a function
 
Hi All,
Please explain this behavior of shell script:
##code section

function myfunc
{
echo "Inside func:PID=$$"
echo "x=$x"
x=23
}

echo "before calling myfunc:PID=$$"
x=12
echo "x="$x
myfunc $x #|tee out.txt
echo "After calling myfunc PID=$$"
echo "x="$x

#### End of code #


runnning the script when not redirecting the output of function
$./script.sh

before calling myfunc:PID=1152
x=12
Inside func:PID=1152
x=12
After calling myfunc PID=1152
x=23
------------------------------------------------------------------------
runnning the script when redirecting the output of function
$./script.sh

before calling myfunc:PID=1152
x=12
Inside func:PID=1152
x=12
After calling myfunc PID=1152
x=9
------------------------------------------------------------------------
Somewhere I read that when o/p of function is redirected to a file using tee ,the function is called in a sub shell,so the value of x modified inside the function is not reflecting in the shell, but the PID
is showing same,so how come one can know that the function is called by a sub shell?
Please explain .
thanks

catkin 01-15-2012 01:35 PM

$$ is not always the current PID. From the Bash Reference Manual: $$ "Expands to the process id of the shell. In a () subshell, it expands to the process id of the invoking shell, not the subshell".

It is for this reason that bash has $BASHPID.

This modified version of your script (to be called with or without the string tee as an argument) illustrates:
Code:

#!/bin/bash
function myfunc
{
    echo "Inside myfunc: \$BASHPID is $BASHPID, \$\$ is $$, x is $x"
    x=23
}

x=12
echo "Before calling myfunc: \$BASHPID is $BASHPID, \$\$ is $$, x is $x"
if [[ $1 = tee ]]; then
    myfunc | tee out.txt
else
    myfunc
fi
echo "After calling myfunc: \$BASHPID is $BASHPID, \$\$ is $$, x is $x"

BTW, your script does not redirect when it uses tee, it uses a pipeline


All times are GMT -5. The time now is 12:28 PM.