3

I'm trying to get my bash function to call another function that uses bash -c. How do we make functions created earlier in the script persist between different bash sessions?

Current script:

#!/bin/bash

inner_function () {
    echo "$1"
    }
outer_function () {
    bash -c "echo one; inner_function 'two'"
    }
outer_function

Current output:

$ /tmp/test.sh 
one
bash: inner_function: command not found

Desired output:

one

two

2
  • upvote for well asked question
    – jsotola
    Commented Oct 7, 2019 at 7:06
  • Why bash -c is necessary within a script that already is executed by bash, if you don't mind me asking ? Commented Oct 7, 2019 at 7:24

2 Answers 2

4

Export it:

typeset -xf inner_function

Example:

#! /bin/bash
inner_function () { echo "$1"; }
outer_function () { bash -c "echo one; inner_function 'two'"; }
typeset -xf inner_function
outer_function

Other ways to write the exact same thing are export -f inner_function or declare -fx inner_function.

Notice that exported shell functions are a) a bash-only feature, not supported in other shells and b) still controversial, even after most of the bugs were fixed since shellshock.

3
  • Thanks for this answer. I'm confused about where to use the typeset command. Should it be outside the outer_function? inside the inner_function? inside the outer_function? I've tried several variations, nothing seems to work.
    – user375954
    Commented Oct 7, 2019 at 7:15
  • It should be before bash -c ' ... inner_function ... command is called. It adds it to the environment.
    – user313992
    Commented Oct 7, 2019 at 7:20
  • @user375954 this is currently implemented by creating an environment variable with a funny name and the source of the function as its value, which will be parsed by bash upon start up. Example: bash -c 'foo(){ echo yup; }; export -f foo; printenv | grep -A1 foo'.
    – user313992
    Commented Oct 7, 2019 at 7:28
0

When I need the same function in several scripts, I put it in a side "library" script file and "source" that (source the_lib_script or . the_lib_script) in the scripts that need the function.

1
  • I appreciate this answer, but I'm trying to keep the script self-contained.
    – user375954
    Commented Oct 7, 2019 at 7:18

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.