Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a bash function be used in different scripts?

Tags:

function

bash

I've got a function that I want to reference and use across different scripts. Is there any way to do this? I don't want to be re-writing the same function for different scripts. Thanks.

like image 498
Herves Avatar asked Jun 19 '09 05:06

Herves


People also ask

How do you call a function in bash script?

To invoke a bash function, simply use the function name. Commands between the curly braces are executed whenever the function is called in the shell script. The function definition must be placed before any calls to the function.

Can we use function in shell script?

It is generally accepted that in shell scripts they are called functions. A function may return a value in one of four different ways: Change the state of a variable or variables. Use the exit command to end the shell script.


2 Answers

Sure - in your script, where you want to use the function, you can write a command like

source function.sh 

which is equivalent to including the contents of function.sh in the file at the point where the command is run. Note that function.sh needs to be in one of the directories in $PATH; if it's not, you need to specify an absolute path.

like image 164
David Z Avatar answered Sep 30 '22 01:09

David Z


Yes, you can localize all your functions in a common file (or files). This is exactly what I do with all my utility functions. I have a single utility.shinc in my home directory that's used by all my programs with:

. $HOME/utility.shinc 

which executes the script in the context of the current shell. This is important - if you simply run the include script, it will run in a subshell and any changes will not propagate to the current shell.

You can do the same thing for groups of scripts. If it's part of a "product", I'd tend to put all the scripts, and any included scripts, in a single shell directory to ensure everything is localized.

like image 45
paxdiablo Avatar answered Sep 30 '22 01:09

paxdiablo