Function behaviour on shell(ksh) script

Posted by footy on Stack Overflow See other posts from Stack Overflow or by footy
Published on 2011-11-29T09:47:26Z Indexed on 2011/11/29 9:49 UTC
Read the original article Hit count: 251

Filed under:
|
|

Here are 2 different versions of a program:

this

Program:

#!/usr/bin/ksh

printmsg() {
        i=1
        print "hello function :)";
}
i=0;
echo I printed `printmsg`;
printmsg
echo $i

Output:

# ksh e
I printed hello function :)
hello function :)
1

and

Program:

#!/usr/bin/ksh

printmsg() {
        i=1
        print "hello function :)";
}
i=0;
echo I printed `printmsg`;
echo $i

Output:

# ksh e
I printed hello function :)
0

The only difference between the above 2 programs is that printmsg is 2times in the above program while printmsg is called once in the below program.

My Doubt arises here: To quote

Be warned: Functions act almost just like external scripts... except that by default, all variables are SHARED between the same ksh process! If you change a variable name inside a function.... that variable's value will still be changed after you have left the function!!

But we can clearly see in the 2nd program's output that the value of i remains unchanged. But we are sure that the function is called as the print statement gets the the output of the function and prints it. So why is the output different in both?

© Stack Overflow or respective owner

Related posts about shell

Related posts about ksh