How to "source" a specific variable

It is possible to scope variables using functions. Example:

## 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

$ cat Consumer.sh
. ./Provider.sh
echo "${map[hello]}"
echo "$a"
$ 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 ''


You can use a function and make the variables local or global:

#!/bin/bash

foo() {
  declare -gA MAP # make global
  local A=hello # make local
  local B=world # make local
  MAP[hello]=world
}

foo

Then:

#!/bin/bash
source ./Provider.sh
[[ -z "$A" ]] && echo "Variable A not defined"
[[ -z "$B" ]] && echo "Variable B not defined"
echo ${MAP[hello]}

Output:

Variable A not defined
Variable B not defined
world

Tags:

Linux

Bash