footy
footy

Reputation: 5931

Function behaviour on shell(ksh) script

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?

Upvotes: 0

Views: 521

Answers (1)

plundra
plundra

Reputation: 19252

When you use backticks (or $(...)), you execute it in a subshell.

That is, a new shell is started (which inherits from the current one) and then exists.

Edit: I checked your link, if you read the bottom of it, the very last section, you'll see this explained.

Upvotes: 2

Related Questions