DEV Community

Henrique Holtz
Henrique Holtz

Posted on

How to create your own functions on Bash

In this article we'll shortly learn how to create your own commands/functions on Bash.

You can use it whatever the OS since you're using a bash-derived terminal like Bash, Zsh, Git Bash and so on.

First of all we'll create the functions. You can choose the file name and its location. In my example I'll create as /home/henrique/my-own-functions.sh (You can use the command touch /home/henrique/ my-own-functions.sh to create the file)

Let's write our first function in the new file:

function MyFirstFunction() {
        echo "Hello World!"
}
Enter fullscreen mode Exit fullscreen mode

Note: To type the function directly in your bash you can use the vim, example: vim /home/henrique/ my-own-functions.sh

After write our function(s) we need to load it in our bash by default, e to do that we need to write a line to load it in the .bashrc file which usually stay in your user's root folder, in my case is at /home/henrique/.bashrc. To load we'll write and save a new line in this file with:

{...}
source /home/henrique/my-own-functions.sh
{...}
Enter fullscreen mode Exit fullscreen mode

After save the change, we need to reopen the bash to verify if our new function is available correctly. To use our new function we'll just type MyFirstFunction and press enter. See the output:

Image description


Extra

You can test your function without need to reopen the terminal using the source command. For example:

source /home/henrique/my-own-functions.sh
Enter fullscreen mode Exit fullscreen mode

Top comments (0)