Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'd like to define it once and use it anywhere.

like image 329
grok12 Avatar asked Jun 02 '11 17:06

grok12


People also ask

How do we define functions in shell scripting?

Creating FunctionsThe name of your function is function_name, and that's what you will use to call it from elsewhere in your scripts. The function name must be followed by parentheses, followed by a list of commands enclosed within braces.

Can we use function in shell script?

A function can be called and reused. In shell scripting, functions are analogous to other programming languages' subroutines, procedures, and functions. Your function's name is function_name , and you'll call it by that name throughout your scripts.

Can a function call itself Bash?

Functions in Bash also support recursion (the function can call itself). For example, F() { echo $1; F hello; sleep 1; } . A recursive function is a function that calls itself: recursive functions must have an exit condition, or they will spawn until the system exhausts a resource and crashes.


3 Answers

While I basically agree with @eduffy, I typically 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. I would then source the file (. ~/FILE or . $(type -p FILE)) in the .bash_profile. This allows you to 're-source' the file if necessary (i.e., you change something in it) w/o having to re-login, etc.

like image 80
Jay Avatar answered Sep 27 '22 23:09

Jay


Place your "common" function in a separate script (let's call it "a"):

#!/bin/bash

test_fun () {
    echo "hi"
}

Next, "import" it into another script (say, "b"):

#!/bin/bash

. ./a

test_fun

Running bash b will output "hi"

like image 29
barti_ddu Avatar answered Sep 27 '22 21:09

barti_ddu


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

like image 27
Amir Afghani Avatar answered Sep 27 '22 23:09

Amir Afghani