Search code examples
bashfunctionglobal-variableseval

Using variables in bash function names


I'm looking for an alternative to eval when declaring functions that include variables in the name. Function names must have a fixed scheme since they're intended to be used in a PKGBUILD. Example:

pkgname=(pkg{1,2,3})
for I in ${pkgname[@]};do eval "package_$I(){
    [ $I = pkg1 ] && echo $I specific stuff
    [ $I = pkg2 ] && echo $I specific stuff
    [ $I = pkg3 ] && echo $I specific stuff
    echo common stuff
    echo common stuff
}";done
package_pkg1
package_pkg2
package_pkg3

Expected output:

pkg1 specific stuff
common stuff
common stuff
pkg2 specific stuff
common stuff
common stuff
pkg3 specific stuff
common stuff
common stuff

Works as needed, except that (from what I was told) eval is not safe to use in this way. What are the alternatives that Bash has to offer?

Edit: Fully working PKGBUILD

Edit 2: Bash script with output

Edit 3: Noted intended use case


Solution

  • I ended up moving the code outside of eval:

    pkgname=(pkg{1,2,3})
    _package(){
        [ $pkgname = pkg1 ] && echo pkg1 specific stuff
        [ $pkgname = pkg2 ] && echo pkg2 specific stuff
        [ $pkgname = pkg3 ] && echo pkg3 specific stuff
        echo common stuff
        echo common stuff
    }
    for i in ${pkgname[@]};do eval "package_$i(){ _package;}";done
    

    This however only works inside a PKGBUILD and will not work with Bash, for which you should take a look into @CharlesDuffy's answer.