How to define a bash function to use in any script?

I would like to define it once and use it anywhere.

+4
source share
4 answers

While I mostly agree with eduffy, I usually put such functions in a file either in the user's home directory, or if the scripts are shared between users in a directory in the user's path. Then I would send the file (. ~ / FILE or. $ (Type -p FILE)) to .bash_profile. This allows you to โ€œredirectโ€ the file if necessary (i.e. change something in it) without having to re-enter the system, etc.

+3
source

In bash, you can run source from your script (with a file containing your functions as an argument) and simply call the function. This happens implicitly when you define a function in your .bashrc .

+3
source

Put it in ~/.bashrc or ~/.bash_profile .

+1
source

Put your "generic" function in a separate script (let it "a"):

 #!/bin/bash test_fun () { echo "hi" } 

Next, โ€œimportโ€ it into another script (say, โ€œbโ€):

 #!/bin/bash . ./a test_fun 

Running bash b displays hi

0
source

All Articles