Search code examples
shellksh

parent sources external file, child doesn't have access to functions within


Scripts in use: parent.ksh, child.ksh, functions.ksh

When the parent sources functions.ksh, then executes ./child.ksh, the functions within the sourced file are not available to child.ksh. Is this always true, or does it matter in the way child.ksh was executed? Child.ksh could source the file, but I'm trying to understand why it isn't working as it's currently configured and how that behavior could be altered.

Read a little about sub-shells and have you invoke different things affects how they behave, but I'm not clear i'm on the right path.


Solution

  • Testing on my laptop under git bash -

    $: cat a
    . c
    foo from a
    ./b
    
    $: cat b
    foo from b
    
    $: cat c
    foo() { echo "$@"; }
    foo from c
    
    $: ./a
    from c
    from a
    ./b: line 1: foo: command not found
    

    However, if I add a line in c:

    $: cat c
    foo() { echo "$@"; }
    export -f foo        # export the function named foo
    foo from c
    
    $: ./a
    from c
    from a
    from b
    

    So, depending on your system, you would need an explicit export of the relevant function name.

    Some parsers may not support this. Good luck.