Nathan Pk
Nathan Pk

Reputation: 749

Need help in calling a function between shell and TCL

Is it possible to call a function in tcl script which is aactually defined in anothe shell script? For example,

my shell script function is

add ()
{
 `a=$1
 b=$2
 c=`expr $a + $b`
`}

How to call this function inside a tcl file? please guide me with this

Upvotes: 1

Views: 683

Answers (2)

Gowtam
Gowtam

Reputation: 505

If your requirement is getting any return value from shell script after performing some functionality i would suggest this method,

--> Define each function in seperate file and Whereever possible in shell script, write the return value to some file in /tmp directory.

filename :: add.sh :::::::::::Give execute permissions for it

function add ()
{
 a=$1
 b=$2
 c=`expr $a + $b
echo $c > /tmp/arg1
}

add $1 $2

:::::::::::::::::::::::::::::::::::

Now open tclsh ,

[root@localhost test]# tclsh
%
% ./add.sh 2 3
% set fp [open /tmp/arg1]
file3
% set value [read $fp]
5

% close $fp
% set value
5

% ^C
[root@localhost test]#

Upvotes: 0

Donal Fellows
Donal Fellows

Reputation: 137757

It isn't really possible to call a function written in another language from Tcl except in a few ways. For example, a C function can be called if it conforms to Tcl's command definition signature, or if some glue code is present (such as might be generated with SWIG or Critcl). The other way to call the code is by invoking it in another process, typically a subprocess. Running the command in a shell script might then be done like this (assuming your function definition is in my_script.sh):

exec /bin/sh -c ". my_script.sh; add 123 456; echo \$c"

But that's rather clunky and inclined to cause problems when dealing with more complicated input values. I advise turning your script into a whole program that can run more directly (so you can do exec my_script.sh 123 456) or, better yet, writing it in some other language which has fewer mysterious gotchas than Unix shell (i.e., most languages!)

Upvotes: 2

Related Questions