Programming in bash - part 3

For, secure our concepts We will learn 2 very useful tools for programming that work perfectly in Bash. Learn to create functions and define pipelines may seem complex at first, but then we will see the immense utility that they provide us.

Table of Contents

Pipes

Specifically, and without taking too many turns, a pipeline is a method that allows directing the output of one process as the input of another, which allows a series of advantages, such as reducing lines of code, dispensing with storage variables for results and improving the efficiency of the script.

A pipe is generally recognized by having the symbol | that allows to concatenate expressions; Although it is used by default, there are other ways to create pipes.

Example: print recent kernel messages

#dmesg allows you to see recent kernel messages and loaded drivers #during system boot; tail prints the last parts of a file or #command

dmesg | tail

Although they can be complicated as much as we want, the basic structure of a pipeline allows the result of one command to be used as input to the next, which can provide input for a new command if we keep adding consecutive pipes.

Functions

Functions are a set of statements that are grouped together so that they can be executed several times without having to rewrite them. It is equivalent to thinking that when we learn to cook a type of food we will write its recipe on a sheet, and every time we want to cook that food we consult the recipe instead of rewriting a new sheet with the same recipe.

Perhaps the most important thing about functions is the possibility of passing parameters, data that they will use to process them and generate an output. Its structure is as follows:

function function-name {

processes,

}

Example: function that shows the services that work on the tcp protocol. We can also see how to apply more pipes.

# We define a function name, it can be the one we like.

function services_tcp {

#cat concatenates and displays the contents of the / etc / services folder, which is # that contains all the services with their associated ports.

#the first grep takes the list and removes the comments, with –v we invert the result

#the second grep shows only those related to tcp

cat / etc / services | grep –v "^ #" | grep tcp

}

When we need to execute this function we just have to call it by its name:

tcp_services

In this case it works without parameters; In the event that it has them, we must add them so that the function works properly, otherwise the function will not work properly. Using return allows a function to return a value as a result of the process.

Example: function with input parameters that calculates the sum of 2 numbers.

#! / Bin / bash
function sum ()
{
# with let we can execute the operation inside the quotes
let "result = $ 1 + $ 2"

#return allows to return the integer value. Once the return is executed, the value will be deposited inside the variable $?
return $ result;
}
 
#The sum function is called and we pass 2 input parameters.

add 2 3

#prints the value of $? with echo evaluating the actual value of the variable in quotes
echo -e "Result = $?";

Thank you Juan Carlos Ortiz!


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

7 comments, leave yours

Leave a Comment

Your email address will not be published. Required fields are marked with *

*

*

  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.   Nill pointer said

    I'm not sure, but the return statement of the functions only serves to return an integer between 0 and 255, like the error codes of "exit", generally 0 if everything is fine and another number for the other cases. Although in the example this works, I don't think it is good practice to return the result with return.
    Over there I'm saying a nonsense huh! eye! ha!

  2.   Juank said

    The truth left me with doubt. In any case, to avoid problems with the functions, we can replace the return with echo in the case that the function seeks to return or print a value or string.

  3.   Abel S. Mount Big said

    It is true, to solve this you can use the bc command, in the sum function you can use: result = `echo $ 1 + $ 2 | bc -ql`

  4.   Luis Miguel said

    Good,

    I would like to know where I can save the bash files so that they run system wide and that is not the bin directory, but can be the home to make backup copies.

    Gracias y saludos.

  5.   Joaquin said

    Thank you very much, I am starting with the scripts, and the truth is that this is very useful, you are very kind to share your knowledge!
    regards

    1.    let's use linux said

      Thank you! Hug!
      Pablo

  6.   CRISTHIAN said

    Syntax error: "(" unexpected
    I get an error when trying to run the example, I copied it exactly the same

    What can be? i am on ubuntu 14.10