Kan Li
Kan Li

Reputation: 8797

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

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

Upvotes: 8

Views: 5742

Answers (4)

Skeptic
Skeptic

Reputation: 1564

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.

Upvotes: 2

lsl
lsl

Reputation: 4419

Call your script with a preceeding dot and space.

. a.bash

Upvotes: 3

evil otto
evil otto

Reputation: 10582

You need to export your functions. You can either export everything when it's created (my preference) with set -a, or you can export the functions individually with export -f showxx. Either will put it into the environment, and child shells will be able to pick them up.

Upvotes: 6

shellter
shellter

Reputation: 37258

You have to define the function to appear in 'scope' of the local process.

When you enter a function onto the command line, it is now 'living' inside the terminal shell's copy of bash.

When you start a script, only variables that are marked with export are visible into the new copy of bash that is running as a child of the terminal. (We won't get into export right now ;-).

To get the function inside your script, you have to define it inside the script.

cat a.bash
#!/bin/bash
function showxx() { echo xx; }
showxx

OR you can put the function in a separate file and 'source' it (with '.'), so it as if it was inside the file, i.e.

 cat    showxx.bfn
 function showxx() { echo xx; }

 cat a.bash
 . showxx.bfn
 showxx

The extension .bfn is just something I use to help document what is inside the file, like bfn= 'bash function'.

The '.' is the source command.

I hope this helps.

P.S. as you appear to be a new user, if you get an answer that helps you please remember to mark it as accepted, and/or give it a + (or -) as a useful answer.

Upvotes: 4

Related Questions