Bash Function – How to Export Functions in Bash

bashfunction

source some_file

some_file:

doit ()
{
  echo doit $1
}
export TEST=true

If I source some_file the function "doit" and the variable TEST are available on the command line. But running this script:

script.sh:

#/bin/sh
echo $TEST
doit test2

Will return the value of TEST, but will generate an error about the unknown function "doit".

Can I "export" the function, too, or do I have to source some_file in script.sh to use the function there?

Best Answer

In Bash you can export function definitions to sub-shell with

export -f function_name

For example you can try this simple example:

./script1:

#!/bin/bash

myfun() {
    echo "Hello!"
}

export -f myfun
./script2

./script2:

#!/bin/bash

myfun

Then if you call ./script1 you will see the output Hello!.

Related Question