I'd like to define it once and use it anywhere.
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.
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.
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.
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.
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With