简体   繁体   中英

In Bash, how can I modify a global variable in a function of a module?

I have a global variable in my script:

export _ERR
. library.sh #import my functions

In library.sh, I would like to set it in function A:

function_a () 
{
  [[ -f /mnt/file.txt ]] && {
    _ERR="Error file does not exist"
  }
}

And later in the main script call function A

output=$(functionA)

and display $_ERR if $ERR is not empty:

[[ -n _ERR ]] && echo ${_ERR}

But _ERR is always empty in my main script.

What am I doing wrong?

By capturing the output with command substitution, you run the function in a subshell. A subshell can't change variable values in the parent shell.

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