user1880760
user1880760

Reputation: 59

pass variables to a function in bash(weird output?)

function f(){
local y=$1;
local z=$2;
echo $x $y $z;
}
function main(){
x=1;
y=2;
z=3;
f $y $z;
}

main $*

My output is 1 2 3

Why does this happen? I only passed two variables y and z.

$1 would be y from main which is 2 so back in function f local y=$1 would be y=2. The same thing for local z=$2, it would be z=3.

So I would assume either an error because I'm trying to echo $x which isn't a valid variable or I should get 2 3.

Why does it echo out 1 2 3?

Upvotes: 0

Views: 109

Answers (1)

DigitalRoss
DigitalRoss

Reputation: 146053

$x is a global variable. The fact that it is assigned within a function doesn't change that.

So of course it is visible in f() or any other function.

Upvotes: 2

Related Questions