How to use functions in bash

How to use functions in Bash using this POSIX-compatible, Unix shell-based computer language. As a language, its function consists of the interpretation of Linux commands, allowing us to automate our repetitive processes and also create commands from the operating system commands. In this article we will review how to use functions in bash. I recommend reading the article how create your own scripts using bash.

In the script that we propose we use the Bash language to search for a file, knowing its name. For this we will use the find command but with the help of the functions previously defined in said script. You have to take into account a peculiarity or limitation of Bash that is not present in all languages: to call a function it must be defined previously.

Define functions

There are two ways to define functions: with or without the function declaration:

function nombre_funcion () 
{
    # codigo
}

or this other one, which is the one I use as you will see later.

nombre_funcion ()
{
    # codigo
}

Also Bash also provides a method to pass parameters and return results. that we will see in future articles.

#!/usr/bin/env bash

# ~/.bin/encontrar
# encuentra archivos a partir de la descripción de su nombre en un directorio específico
#
# Por Pedro Ruiz Hidalgo
# version 1.0.0
# Copyright © enero 2017
#
#

EXIT_OK=0
EXIT_BAD=66

PATRON=$1
DIRECTORIO=$2

autor ()
{
 echo -e "\nPedro Ruiz Hidalgo @petrorum. Copyright © 2017\n"
}

ayuda ()
{
 echo -e "\nencontrar [PATRON] [DIRECTORIO]\n"
} 

noparams ()
{
 echo -e "\nSon necesarios dos parámetros\nencontrar -h para ayuda\n"
 read -p "¿Quieres ver la ayuda? (S|s)" -n 1 -r
 if [[ $REPLY =~ ^[Ss]$ ]];
    then
       echo ""
       ayuda
 fi
}

nodir ()
{
 echo -e "\nDirectorio no Existe\n"
}

if [[ $PATRON == "-h" ]];
then 
 ayuda
 exit $EXIT_OK
fi

if [[ $PATRON == "-a" ]];
then 
 autor
 exit $EXIT_OK
fi

if [ $# -lt 2 ];
then
 noparams
else
 if [ -d $DIRECTORIO ];
 then
 echo ""
 find $DIRECTORIO -name $PATRON*
 echo ""
 exit $?
 else 
 nodir 
 exit EXIT_BAD
 fi
fi


Script analysis

Definitions

For bash every process completed successfully must have the code "0" as a signal. Lines 12 and 13 define the error codes handled EXIT_OK for success y EXIT_BAD for exit on failure.

In lines 15 and 16, the PATTERN and DIRECTORY variables are assigned the first ($ 1) and second ($ 2) parameters that appear on the command line after the name of the script, as we will see later when we execute it.

Here at the 18 line we create our first function. The function called «author» displays the script authorship when we call it with the "-a" argument as you can see in the if on lines 50 ~ 54. The argument "-E" from line 23 allows to show the sequence of «next line» by encoding «\ n».

The call to noparams (lines 28 ~ 37) is in charge of managing the events that must occur when the script is called without any parameters. We show, properly enclosed between new line codes, a message indicating that the script must be executed with two parameters, then an option (line 31) is shown to use read It prompts you to press "S" or "s" in case you want to show help. In line 32 we literally say: 'if the answer (that comes to us in the variable $ REPLY) contains any of the characters that uppercase or lowercase ', then (line 33) shows an empty line (line 34) and executes the help function (lines 23 ~ 26).

The nodir function (lines 39 ~ 42) will be executed when we detect that the directory where the search is being attempted does not exist.

Functionality

With this we already have defined all necessary functions to run our program, which actually starts at line 44, checking if the first of the parameters that the script receives is "-h". exits indicating normal termination.

If PATTERN (first parameter as described in line 15) is "-a", the author is displayed following the same mechanism explained in the previous paragraph for the "-h" option.

On the line 56 it is controlled that we have not received less than two parametersIn this case, the noparams function is executed, then in the if of line 60 we find out if the directory on which we want to do the search exists, if it exists, an empty line is shown, the find command with the address of the directory on which we want to carry out the search followed by the pattern (beginning of the name of the file we are looking for) a new blank line and using exit$? we entrust the output of our script to the result produced by find. In case the condition of directory existence is false (line 67) we make a call to the nodir function and we exit indicating an abnormal termination.

Execution and testing

$ encontrar
$ encontrar -a
$ encontrar -h
$ encontrar index aljflaskjf #directorio no existe
$ encontrar index public_html
$

En following articles about Bash we will see the mechanisms for use parameters in functionsWe will also see how to articulate return data thereof.

I hope and hope that this post has been useful for you.


The content of the article adheres to our principles of editorial ethics. To report an error click here!.

A comment, leave yours

Leave a Comment

Your email address will not be published.

*

*

  1. Responsible for the data: Miguel Ángel Gatón
  2. Purpose of the data: Control SPAM, comment management.
  3. Legitimation: Your consent
  4. Communication of the data: The data will not be communicated to third parties except by legal obligation.
  5. Data storage: Database hosted by Occentus Networks (EU)
  6. Rights: At any time you can limit, recover and delete your information.

  1.   Josiah said

    Hello,
    very interesting and very clear.
    Just a note; a $ is missing on line 68 in front of the variable EXIT_BAD.
    I will continue to learn for sure with your articles.