Last Updated: February 25, 2016
·
544
· destructuring

Mapping function outputs to names

Setting variables to the output of some function or command where the variable names, function names are dynamic is useful for reading in a configuration file or string.

If you can construct the variable and function name into strings, use the following vset function:

function vset {
  for p in "$@"; do
    nm_fn="fn_${p}"
    nm_var="var_${p}"
    eval "$nm_var=\$($nm_fn)"
  done
}

Calling vset like:

vset ssh git pwd

assigns three variables like the following hardcoded assignments:

var_ssh=$(fn_ssh)
var_git=$(fn_git)
var_pwd=$(fn_pwd)

Dynamic variable names are good for plugins. Say my cue library for shell prompts accepts variables named $vargit, $varssh, vset can set those variables by calling prompt-git, prompt-ssh, whether they are just in the $PATH or functions defined outside of my cue library.