paperlined.org
apps > bash
document updated 11 years ago, on Jun 28, 2012
Is it possible to have anonymous functions in Bash?

    function anonfunc { (( anonfunc_cnt++ )); eval "function anonfunc$anonfunc_cnt { $1; }"; echo "anonfunc$anonfunc_cnt"; } 


That SEEMS like it should work:

    > anonfunc 'echo hi there' 
    anonfunc1

    > anonfunc1
    hi there


But it falls apart at a crucial point:

    > funcname=$(anonfunc 'echo hi there')

    > echo $funcname
    anonfunc1

    > anonfunc1
    command not found


The reason?  $(...) means it runs in a subshell, in a separate process, so any changes made there don't stick:

    > echo $(anonfunc 'echo hello there')
    anonfunc1

    > echo $(anonfunc 'echo hello there')
    anonfunc1

    > echo $(anonfunc 'echo hello there')
    anonfunc1