fronthem
fronthem

Reputation: 4139

Set a value to global variable from a subshell

Code example main.zsh:

#!/usr/bin/env zsh

. ./my_script.zsh

my_global_var=""

output=$(my_func)

Code example my_script.zsh:

#!/usr/bin/env zsh

my_func(){
    my_global_var="hello!" # doesn't work!
    echo "my output" # return value
}

In this case how can I set a value to my_global_var from my_func in a subshell. What I try to do here, I just try to implement a function concept in zsh which be able to return a value via variable substitution mechanism $() but the problem is if I implement it in this way, I will not be able to access global variable from my function. I'm quite confusing now, maybe I get into the wrong way to implement a function concept in zsh.

Upvotes: 1

Views: 2095

Answers (2)

fronthem
fronthem

Reputation: 4139

Thank you @chepner for your answer, BTW, I would like to purpose an alternative way to solve this problem. Many people have talked about "return multiple variables", in the same way, here I will purpose you an "eval trick"

Code example main.zsh:

#!/usr/bin/env zsh

. ./my_script.zsh

my_global_var=""
output=""

temp=$(my_func)
eval $(echo $temp) # become: set_vars "hello!" "my output"

Code example my_script.zsh:

#!/usr/bin/env zsh

my_func(){
    echo 'my_global_var="hello!"; output="my output"' # return values
}

Upvotes: 1

chepner
chepner

Reputation: 531045

You can't. my_func runs in a separate process, so whatever it does to my_global_var is local to that process, unseen by main.zsh. Your function can either be used to set global variables or output text intended to be captured by $(...), not both.

Upvotes: 3

Related Questions