views:

40

answers:

2

This is, perhaps, a silly question, but it's something that I've wondered about: is it possible to, say, define a Ruby/Python/Perl/etc. function in some file and then source it in Bash (to make it available anywhere in the current shell)?

At the moment, I "source" scripts/functions in other languages by creating a bash alias that executes that script... But I wonder if it's possible for Bash to interpret those other functions directly?

Thanks. :)

+1  A: 

Nope, it's not that easy to do that!

You could write something that knows how to execute a given function in a given file (using the language's interpreter), but that goes beyond bash :)

LukeN
Well that's a shame. ;)
ABach
Hey, you could see this as an opportunity to improve in your weakest language by implementing all those functions in that one :)
LukeN
That's a good point - it's just hard to "reduce" myself to Bash when something like Perl is so tantalizing. But that's a bit pompous, so I'd better get over it!
ABach
+1  A: 

It's not that hard. You have to take advantage of the language's features for specifying what code to run. Figuring out how to escape the code and the input is tricky. But its doable:

# source-lang.sh: define some bash functions that call other languages
perl_sqrt()
{
    export operand=$1
    perl <<'EOF'
        print sqrt($ENV{operand}),"\n"
EOF
}

python_log()
{
    a=$1
    b=$2
    if [ "$b" = "" ] ; then
    b=$a
    a=10
    fi
    python <<EOF
import math
c = math.log($b) / math.log($a)
print c
EOF
}

$ source source-lang.sh
$ perl_sqrt 289
17
$ python_log 2 128
7.0
$ f=`perl_sqrt 1024`
$ echo $f
32
mobrule
Ahh, I see... That makes good sense. Thanks!
ABach
Hmm, looks like I was talking nonsense down there. Forgive me! :)
LukeN