Higher order functions in bash

Jul 13, 2007 10:07

I recently had occasion to refactor a bunch of bash scripts, and one of the problems was that certain loop constructs were cropping up a lot. A quick search didn't turn up a way to do higher order functions in bash, so I (re)invented one:

higher_order() {
# some code
eval "$1"
# some more code
}The eval evaluates the code passed as a ( Read more... )

geekery, programming, linux

Leave a comment

Comments 4

msmercenary July 13 2007, 17:34:08 UTC
I started doing this in mIRC about four years ago, and my scripts became an order of magnitude cooler overnight. Schlockbot and servernotices make a lot of use of this type of metafunctionality.

Of course, all my mIRC script messing around culminated in the PiBot, so there's clearly risk involved.

Reply

jerith July 14 2007, 09:14:15 UTC
Updated with pointer to a more complete version on my website.

I wouldn't use most of this stuff in anger, though. By the time it's necessary, I've usually switched to a different language. The only reason I did it in this case was that I was writing system build scripts and I can't assume that anything other than the most basic tools are available.

Reply


Why eval? anonymous July 31 2007, 19:25:44 UTC
Why use eval at all?

You could simply do:

$ FOO="hello world"
$ $FOO
$ $FOO

No?

Alejo, from http://azul.freaks-unidos.net/

Reply

Re: Why eval? jerith August 1 2007, 07:59:19 UTC
Partly because it makes what I'm doing a little more explicit and partly because I didn't thing of the other way until I'd already written the code.

Reply


Leave a comment

Up