Bash: Conditions (if-then-else)

Hello

This time I will show you how to make a script with condition in Bash, which translated is:

If X thing you want is done, Y action is done, if it is not done then another action is done.

Simple explanation no 😀

Now, I have thought for a few minutes about some example to use in this tutorial, the following dilemma / problem / situation occurred to me:

We are on our company's network, and we want to know if X computer is connected to the network. For this we make a script what will he do ping towards that computer, and if it is on a network (that is, if it returns the ping) will tell us that YES, it is on the network, otherwise (that is, it is not on the network) it will tell us that it is NOT on the network.

Once this is done, now I will explain how to cycle with conditions 🙂

Here is the code:

ping -c 1 DIRECCION-IP
if [ $? -ne 0 ]; then
echo "No está en red"
else
echo "Sí está en red"
fi

Don't worry, I'll explain this to you in detail 😉

ping is the command we will use, and it will tell us if that PC is on the network. To tell which PC we want to check whether or not it is on the network, we must change IP ADRESS by obviously, the IP address of the PC that we want to check.

As you can see, I put «-c 1«, Which is necessary to us. When we ping a computer, this action does not stop (the ping) until we press ourselves [Ctrl] + [C], so putting «-c 1»We tell it to do only one verification (only one ping attempt) and no other, this will make it stop instantly, that is… it will check if the computer is on the network only once.

If you have doubts about this, no pain ... they say so and I will be happy to explain it to you again 😉

Now comes the cycle, because what I just explained is nothing more than a normal command / action 😀

if [ $? -ne 0 ]; then
echo "No está en red"
else
echo "Sí está en red"
fi

So that you understand this, I will explain an extremely important detail of Bash 🙂

The most knowledgeable of the subject could brand me as wrong or something like that, but hey, I write this for the novices or less experts, as long as they understand it then great 😉

It happens that as in Bash it's something like 0 y 1, that is, either you are alive or you are dead, when a command or action is executed: Either executed well No problem (1), Or there was some problem or error (0).

We carry out X action or command, and what we did may have been carried out well or badly, it may have had an error or not, and this is where the detail is 😉

If what we send to do (in this case: ping -c 1 IP-ADDRESS) did not give an error and it was successful, so it will return the value: 1 . Otherwise, and if the action (that is, the ping) was not successful, it will return value 0.

 And finally, what the above code means is this:

If value 0 was returned then

Display the text: «Not on network»

Otherwise (and NOT 0, but 1 is returned)

Display the text: «If it is in network«

This that I have just explained to you, will serve us in the future for many things, because it is really useful to be able to say that if X action gave an error, do Y action, and in case X action has not given an error, then do Z action.

I know that some might get a bit confused, so I have tried to explain it in several different ways, trying to make everyone understand it one way or another. In case anyone is left in doubt, let me know.

Now, let's make our script 😀

We must follow the steps in this tutorial: Bash: How to make an executable script

Then let's copy the following code into that file (script.sh), and at the end let's say «exit»(Without the quotes):

ping -c 1 DIRECCION-IP
if [ $? -ne 0 ]; then
echo "No está en red"
else
echo "Sí está en red"
fi

It should look like this (remember that they must have changed the IP-ADDRESS to the IP they want):

Here you can see the running script:

% CODE1%

As you can see, in the end he tells us «Yes it is in network»🙂

The important thing here is that they actually understand this about the conditions, so I leave you another code to explain it again, but from another point of view.

read "texto"
if [ "$texto" = "3" ]; then
echo "Correcto"
else
echo "Incorrecto"
fi

What this means is simple, I leave the explanation line by line:

1st line: What we write, that will be the value of the variable «text»(Without the quotes).

2nd line: Check if the content of the variable (what we just wrote) is 3.

3st line: In case of being 3, it will show us the text «Correct»(Without the quotes).

4th line: Otherwise (that is, in case we have not written 3).

5th line: It will show us the text «Incorrect»(Without the quotes).

6th line: End of condition.

As they have been able to realize, if we put threw out and then between double quotes («) a text, this will cause that text to be displayed in the terminal. That is, if we put:

echo "esto es una prueba"

It will show us the text in the terminal: this is a test

But going back to this second example, I will show you the usefulness (and execution) of this second script with something VERY simple 😀… the typical «how much is 1 + 2?«

I leave the code of the complete script:

#!/bin/bash
# -*- ENCODING: UTF-8 -*-
echo "¿Cuánto es 1 + 2?"
read "texto"
if [ "$texto" = "3" ]; then
echo "Correcto"
else
echo "Incorrecto"
fi
exit

Here is how the script works:

% CODE2%

And well ... nothing more to add.

This is something elementary, simple yes, but still I have tried to explain it as well as possible, because not everyone has the soul of a programmer, and many times we need to make scripts like these (or similar), in any case I hope this article is useful someone 🙂

Any doubt or question, complaint or suggestion please leave it here, I will gladly answer you and thus, we all learn a little more 😀

regards


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.   jhals said

    You are a pro !!! *or*

    1.    KZKG ^ Gaara said

      Nah for nothing 😀
      If it served you and it is interesting, I am satisfied 😉

      Greetings friend

  2.   proper said

    @ KZKG ^ Gaara,
    speaking of bash programming I have a question:
    What is the difference between declaring a variable like this VAR = hello and declaring it like this VAR = $ {VAR: -hello}?

    I explain:
    http://pastebin.com/a3cfWXeD

    greetings 😉

    1.    KZKG ^ Gaara said

      Hello
      Well, I'm not an expert in bash at all ... actually, I have no idea LOL !!
      As I declare the variables it is like this:
      : ${OPTFOLDER:="/opt/"}

      But because I always did it like this, I don't know what the difference could be honestly 🙁

  3.   proper said

    @ KZKG ^ Gaara
    Well I asked the question because the truth is that I didn't know either, I usually write SlackBuilds and the truth is that variables declared as in VAR1 abound in these scripts. A quick google search helped me to clarify this question, I share it with everyone so that we can all learn:

    script:
    http://pastebin.com/faAQb35w

    Explanation:
    Declaring variables of the form VAR = $ {VAR: -default_value} means that the variable VAR will take the value default_value if and only if the value is null or does not exist.

    Practical example:
    When executing the script, it is asked to enter a value to be stored in the VAR variable, if something is entered it will show what was entered. If we do not enter anything and press enter we are declaring the variable VAR as null, therefore it shows value_default.

    Greetings.

    1.    KZKG ^ Gaara said

      HAHA I didn't know that 😀
      Ok, thank you very much friend ... that is what I meant by the end of the article, I do not intend to teach something and that's it, I know that I will always learn something new here 😀

      Greetings and thanks once again.

      1.    proper said

        you're right, one learns several things here.

        greetings and happy holidays !! 😀

  4.   Lucas Matthias said

    Terrific and excellently explained +1, the time it will have taken you ...
    but I'm worth the effort 😉

    1.    KZKG ^ Gaara said

      Actually I wrote 80% in just 1 day, it took me so long to publish it just because my internet would not let me.
      Thank you for your comment 😉

  5.   Hugo said

    Another way to do it is using DNS, since sometimes networks have ICMP protocol blocked:

    (host -ta IP-ADDRESS> / dev / null 2> & 1) && echo "Connected to network"

    You will also notice that in this example the return value check is implicit 😉

    1.    KZKG ^ Gaara said

      You as always friend, with tips that I do not know completely HAHAHA.
      Thank you, the comment is appreciated and hehe ... another new thing that I learn 😀

  6.   Date said

    Thank you

    : )

  7.   Leper_Ivan said

    Even though several days have passed since the publication of this topic, it has served me a lot, now that I made a script in bash .. Thanks Gaara ..

  8.   Edgar navarro said

    Doc. Thanks for the help you made things clear for me.

    Just a query, how do I do so that when one computer stops pinging automatically the other changes IP. I have this.

    to change the IP
    #! / Bin / bash
    ping -c 10 192.168.1.50 # if it doesn't ping automatically
    ifconfig eth0 192.168.1.50 netmask 255.255.255.0 broadcast 192.168.1.0
    ifconfig eth0 down
    ifconfig eth0 up

  9.   Abraham said

    because when comparing with the if you use the question mark? what difference is there between putting the? any other letter

    1.    KZKG ^ Gaara said

      $? means 'the previous output or output', that is, in case the result of the previous command ... 🙂

      1.    Andrés said

        There is another way to achieve the same result, passing the ping command directly as an argument to if:

        if ping -c 1 IP-ADDRESS; then
        echo "Yes it is on the net"
        else
        echo "Not on the network"
        fi

        What happens is that if evaluates the return value of the command that you pass as an argument, if it returns 0 it is true, anything else is false. The square brackets are equivalent to the test command. But you can pass any command as an argument (as long as the command returns some value).

  10.   regards said

    Hello, how do I execute a script.sh with a user X in the script I create a user Y, and that user Y continues executing the script.sh

    Can this be done ??

  11.   kuktos said

    Very interesting, thanks!

  12.   Francisco said

    Thanks for the contribution, I have been an hour to understand it xD, but I understood it !!!!.

  13.   Eloy said

    The script is fine. Arithmetically it could also be done as ($? == 0) if it is equal to zero it is not on the network, otherwise it is on the network. And if we still want to make it a little more interactive we can say:
    echo -n Enter the IP:
    read ip
    ping -c 1 $ ip

  14.   Dario said

    Hello, I am very new to this, I am trying to make a ticket number (alphanumeric) through a read and I want that if what is entered has the correct format (ABC-123456) execute an "x" command and I don't know how to do it, could you help me?

    echo "Enter ticket"
    read -p ticket

    if $ ticket = "no idea (format ABC-123456"); then cp file.txt $ ticket; else echo "wrong format, try again"; read -p; fi.

    Sure it's horrible and they laugh haha, but like I said I'm just starting with this.

    If I explain badly please tell me and I try to do better.

    Hug everyone.

  15.   Umberto Y said

    Excellent explanation, greetings

  16.   agile said

    I have a little doubt with if, else and others.
    I want a script to check that a file exists (one of logs) and if not, to create it and later write to it. But if it exists, I want you to just write to it.

    What I have is:

    date = `date -R`
    #I was testing variable date, which is not updated between the start of a
    #process and ends, sometimes an hour can pass and the correct time does not come out.

    if [-f /home/user/logs/test.log];
    then
    touch /home/usuario/logs/test.log
    else
    echo "$ date: Updated" >> /home/user/logs/test.log
    echo «———————————————-» >> /home/user/logs/test.log
    fi

    In theory it should be fine, but the reality is that it is not updated if the referenced file already exists

    1.    agile said

      sorry, I saw that it was not sent and it has doubled