Search code examples
bashdeclare

declare [nameref] as pointer to function, fails


I want to be able to make a nameref pointer to a function name, using bash declare -n.

Code below demonstrated what i expected should work.

#!/bin/bash
  declare -fx _myfunc
  declare -nx myfunc=_myfunc
  _myfunc() {
    echo "123"
    return 0
  }
  echo "myfunc: $(myfunc)"
  echo "_myfunc: $(_myfunc)"

expected result:

myfunc: 123
_myfunc: 123

actual result:

myscript: line 9: myfunc: command not found
myfunc: 
_myfunc: 123

Solution

  • You are not accesing the variable myfunc (with ${myfunc}). But you also have to dereference it since it is a pointer to _myfunc.

    So, it should be:

    ...
    echo "myfunc: $(${!myfunc})"  <--- this changes
    echo "_myfunc: $(_myfunc)"
    

    and then you will get:

    myfunc: 123
    _myfunc: 123