views:

77

answers:

2

I am writing a bash script that calls functions declared in the parent shell, but it doesn't work.

For example:

$ function myfunc() { echo "Here in myfunc" ; }
$ myfunc
Here in myfunc
$ cat test.sh 
#! /bin/bash

echo "Here in the script"
myfunc
$ ./test.sh 
Here in the script
./test.sh: line 4: myfunc: command not found
$ myfunc
Here in myfunc

As you can see the script ./test.sh is unable to call the function myfunc, is there some way to make that function visible to the script?

+11  A: 

Try

$ export -f myfunc

in the parent shell, to export the function.

unwind
Now, that I did *not* know.
Andrew McGregor
@Andrew: Right! There are some answers that just can't be improved upon.
Charles Stewart
+2  A: 

@OP, normally you would put your function that every script uses in a file, then you source it in your script. example, save

function myfunc() { echo "Here in myfunc" ; }

in a file called /path/library. Then in your script, source it like this:

#!/bin/bash
. /path/library
myfunc
ghostdog74