如何“获取”特定变量

Mic*_*oni 4 linux bash

假设我有两个 bash 脚本:

Provider.sh,它执行一些过程并需要“公开” MAP,但不是Aor B:

#!/bin/bash
declare -A MAP
A=hello
B=world
MAP[hello]=world
Run Code Online (Sandbox Code Playgroud)

Consumer.sh,它执行Provider.sh并需要使用MAP.

#!/bin/bash
source ./Provider.sh
echo ${MAP[hello]}  # >>> world
Run Code Online (Sandbox Code Playgroud)

为了尽可能地整理环境,我希望尽可能少Provider.sh地看到Consumer.sh. 如何才能做到只有 MAP 是“来源”的。

gue*_*est 7

可以使用函数来限定变量的范围。例子:

## Provider.sh
# Global vars
declare -A map

# Wrap the rest of Provider.sh in a function

provider() {

    # Local vars only available in this function
    declare a=hello b=world c d


    # Global vars are available
    map[hello]=world

}

provider "$@"    # Execute function, pass on any positional parameters

# Remove function
unset -f provider
Run Code Online (Sandbox Code Playgroud)
$ cat Consumer.sh
. ./Provider.sh
echo "${map[hello]}"
echo "$a"
Run Code Online (Sandbox Code Playgroud)
$ bash -x Consumer.sh
+ . ./Provider.sh
++ declare -A map
++ provider
++ declare a=hello b=world c d
++ map[hello]=world
++ unset -f provider
+ echo world
world
+ echo ''

Run Code Online (Sandbox Code Playgroud)