Herves
Herves

Reputation: 541

Can a bash function be used in different scripts?

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.

Upvotes: 43

Views: 25672

Answers (3)

Aliabbas Kothawala
Aliabbas Kothawala

Reputation: 23

Yes..you can! Add source function_name in your script. I prefer to create variable eg.VAR=$(funtion_name),if you add the source function_name after #!/bin/bash then your script first execute imported function task and then your current script task so its better to create variable and used anywhere in script. thank you..Hope its work for you:)

Upvotes: -4

David Z
David Z

Reputation: 131550

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.

Upvotes: 82

paxdiablo
paxdiablo

Reputation: 881103

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.

Upvotes: 14

Related Questions