Skip to content

Instantly share code, notes, and snippets.

@andyneff
Last active November 11, 2019 23:14
Show Gist options
  • Select an option

  • Save andyneff/3de3c8a91bc1a1aa909135328cfe1863 to your computer and use it in GitHub Desktop.

Select an option

Save andyneff/3de3c8a91bc1a1aa909135328cfe1863 to your computer and use it in GitHub Desktop.
Tricks on how to do bash variable indirection

Indirection

Setting a variable

  1. A "local" variable, that will be local to the function
var=foo
value="b a  r"
declare "${var}=${value}"
  1. A "global" vairable, that will be set outside a function
var=foo
value="b a  r"
export -n "${var}=${value}" # Compatible with bash 3.2, use this one. Does not work on arrays prior to bash 4.2
# https://stackoverflow.com/q/10806357/4166604
# declare -g "${var}=${value}" # Not compatible with bash 3.2, only bash 4.2 or newer
  1. An exported variable, that will be inherited by child processes
var=foo
value="b a  r"
export "${var}=${value}"

Setting an array

I want to conditionally set an array when it is unset, I have made a one liner for an array, using a function o replicate : ${FOO=BAR} for arrays:

function set_array_default()
{
  local default="$1"
  shift 1
  
  if ! declare -p $default &> /dev/null; then
    local IFS=''
    if [ "${BASH_VERSINFO[0]}${BASH_VERSINFO[1]}" -ge "42" ]; then
      declare -ag "${default}=()"
    else
      eval "${default}=()"
    fi
    for (( i=0; $#; i++ )); do
      read -r "${default}[$i]" <<< "${1}"
      shift 1
    done
  fi
}

set_array_default foo bar "B A  R"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment