简体   繁体   中英

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?

$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM