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

For example, the following commands do not work. I wonder how to get around this, 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 
+7
source share
3 answers

You need to export your functions. You can export everything when it is created (my preference) using set -a , or you can export functions individually using export -f showxx . Or put it on Wednesday, and child shells will be able to pick them up.

+5
source

You must define a function to display in the scope of the local process.

When you enter a function on the command line, it now "lives" inside a copy of the bash terminal shell.

When you run the script in a new copy of bash, only the variables marked with export are visible, which works as a child terminal. (We will not go into export right now export .

To get a function inside your script, you must 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" (with "."), So that as if it were inside the file, i.e.

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

The .bfn extension is what I use to help document what is inside the file, for example bfn = 'bash function.

"." is the original team.

Hope this helps.

PS as you, it seems, a new user, if you get an answer that helps you remember to mark it as accepted and / or give it + (or -) as a useful answer.

+3
source

Call the script with a leading dot and a space.

. a.bash

+1
source

All Articles