What is a function?
A function in Bash is like a function in any programming languages. A function is a subroutine in a program, and though I wont go into detail on that here you can learn more about it at wikipedia.
In bash the syntax to create a function is really simple, here is an example.
This creates a function called
sayHello that, when called, will echo “hello” to the screen.
To call this function inside a script is also simple, you treat
sayHello as though it is a
command that you would call just like any other in the script. For example:
This output of this script will be this.
about to call the function hello done
sayHello function, when called, will just execute the code that is inside the function and move on.
What can you do with functions?
Functions can be handy for a lot of reasons.
You can send the output from the function to a file instead of standard output. For example you could change the script to this:
This will take the output from the
sayHello function and send it to file.txt.
Replace Complicated Commands
You can take a command that is annoying to type over and over and put it into a function that makes it easier to call. For example:
This function can take in a string and return the string with only lowercase letters. To use this function in a script you would write it like this.
The output from this script will be…
this sentence is terrible to look at!!
And as you can see it is no longer terrible to look at anymore :)
NOTE: The function must be created in the script before it is called in the script! Otherwise the script will say the command doesn’t exist. To remedy this I make all of my functions at the top of the script.
You can create on usage error in your script (the output you see when you call a program
--help switch normally). This can be helpful because you can call the
function to print the usage for multiple reasons, such as calling it with the
or supplying an incorrect argument, etc.
When a function gets called, it gets executed the exact same way a program or script would get executed. This means that you can pass command line arguments to the function the same way you would with a script, and you would read them the same way. For example.
This script will set a the variable VARIABLE to “test”, and will then pass it into the function
This function can then reference that variable by using the variable
$1, because it was passed to the
function as an argument. If the variable is empty it will print “empty”, otherwise it will print “NOT empty”.
When to use functions
This rule is not set-in-stone, but more or less a rule of thumb. If you’re going to use the same code more than once in a script, consider if it would be better to write the code once in a function, and call that function multiple times.