R4F6 R4F6 - 7 months ago 20
Bash Question

Bash: exported function not found in another script

I am trying to write a unix script that has the structure below. Basically, I want to have a "Library" script of functions that I use all the time, and export all the functions using

export -f functionName
. The actual script using the library functions would first run the library script to perform the export commands and would then theoretically have access to the functions just exported. However, this does not work as shown by the error. Both scripts have been
chmod 777
'ed for testing. I am literally trying these examples below. These are not substitutes for some prod code somewhere. I copied and pasted what I am trying.

LibraryFunctions.sh:

#!/bin/bash

function getHelloWorldString() {
echo "Hello World"
}
export -f getHelloWorldString


TestLibraryFunctions.sh

#!/bin/bash

./LibraryFunctions.sh

function testExportedHelloWorld () {
echo $(getHelloWorldString)
}
testExportedHelloWorld


Result:

me@myHost:~/testDir $ ./TestLibraryFunctions.sh
./TestLibraryFunctions.sh: line 6: getHelloWorldString: command not found


Edit: Solution that worked for me:

Removed
export -f getHelloWorldString
from LibraryFunctions.sh

Removed
./LibraryFunctions.sh
from TestLibraryFunctions.sh

Added
source LibraryFunctions.sh
from TestLibraryFunctions.sh at the top

------- New files ------:

LibraryFunctions.sh:

#!/bin/bash

function getHelloWorldString() {
echo "Hello World"
}


TestLibraryFunctions.sh

#!/bin/bash

source LibraryFunctions.sh

function testExportedHelloWorld () {
echo $(getHelloWorldString)
}
testExportedHelloWorld


Thanks all!

Answer

Exporting a variable or function only makes it available in child processes of the shell that performed the export. When you execute a command, including running a shell script, that script runs in a child process. So you're running LibraryFunctions.sh in a child of the original TestLibraryFunctions.sh process. When you get back to the original script, you're not in a child of LibraryFunctions.sh, so exported functions are not visible.

If you want to run a shell script in the same process as the current process, use the source or . command to execute it.

source LibraryFunctions.sh

Note that if you do this, you don't need to export the function, since the definition happens in the same shell process, and there are no child shell processes that need to use it.