[Bash-completion-devel] Passing variables by reference

Freddy Vulto fvulto at gmail.com
Sun May 9 20:57:54 UTC 2010


The way we now do "passing variables by reference" (working around the conflict
with local variables) felt a bit awkward so I put my workaround to the test on
the bug-bash mailing list.

After having discovered some surprising (at least for me) behaviour of `unset'
the final outcome seems to be an elegant solution, similar to Tcl's `upvar':

    upvar() { unset -v "$1" && eval $1=\"\$2\"; }
    blackbox() { local "$1" && upvar $1 bar; }
    f() { local b; blackbox b; echo $b; }
    f  # Ok: b=bar

If anyone wants to read and/or contribute, the thread is:
http://www.mail-archive.com/bug-bash@gnu.org/msg07285.html

I'm summarizing the solution here:
http://fvue.nl/wiki/Bash:_Passing_variables_by_reference

and explaining the behaviour of `unset' here:
http://fvue.nl/wiki/Bash:_Unset

I'll do some further testing and if things look all right I'll apply the
`upvar' solution to bash-completion, getting rid of the additional call-layer
in:
- _get_comp_words_by_ref > __get_comp_words_by_ref
- __get_cword_at_cursor_by_ref > ___get_cword_at_cursor_by_ref

BTW, I'm trying to reuse the bash-completion test suite for testing standalone
bash solutions like this, but reusing the bash-completion test suite is not
straightforward at the moment.  Perhaps somewhere in the roadmap we can try
thinking about separating the test suite into a standalone project?  I think
this would benefit other bash projects (they'll have a test suite) and
bash-completion (the test suite would become better).


Greetings, 

Freddy Vulto
http://fvue.nl



More information about the Bash-completion-devel mailing list