shell - Bash global variables not changed when functions is evaled -
i want call function "b" , pass funcion name (a1, a2, etc), called it. , in function, name passed, initialize several variables, can't read them "b" function.
function a1 { echo "func 1" result1="a1" return 0 } function a2 { echo "func 2" anotherresult="a2" #..some other initialization return 0 } #... function b { output=`$1` # $1 - function name echo output=$output echo result1=$result1 # <--- error! result1 empty! } b "a1" # main script runs function b , passes other function name
your function b not call a1.
note output=$($1) not expect, because whatever running inside $(...) executed in different process, , when process terminate, value set not accessible longer.
so:
function b { output=\`$1\` # <-- not call $1 print output=`$1` # <-- ( $($1) better style ) - call whatever # inside $1, in process $1 # <-- here missing call in current process. ... } you can use redirection e.g. a1 > tmpfile file or named pipe, @ output via file-system while keeping side-effect in current process:
function b { $1 > tempfile read output < tempfile echo output=$output echo result1=$result1 } will expect, use tempfile on file-system.
Comments
Post a Comment