In a bash script, how to run bash functions defined outside?

Viewed 4667

For example, the following commands doesn't work. I wonder how to work around it, thanks.

[liuke@liuke-mbp ~]$ function showxx() { echo xx; }
[liuke@liuke-mbp ~]$ showxx
xx
[liuke@liuke-mbp ~]$ cat a.bash 
#!/bin/bash
showxx
[liuke@liuke-mbp ~]$ ./a.bash 
./a.bash: line 2: showxx: command not found
4 Answers

Lets say that your script is myscript.sh with the contents below:

#!/bin/bash

if [ "$#" -gt 0 ]; then
    export command=$1
    foo() {
        echo "foo function run"
    }
    bar() {
        echo "bar function run"
    }
fi
$command

If you execute ./myscript.sh foo , then the foo function gets executed. If you execute ./myscript.sh bar then the bar function gets executed.

Related