Programming in bash - part 2

Second This mini-tutorial programming in Bash, where we learn to use ciclos and other tools that will help us improve the functionalities of our scripts.

The If conditional

The function of If is to apply a filter and perform an operation or task for each type of filter applied. Its structure is as follows:

If [condition]; then elif commands [condition]; then else commands; fi commands

An example is shown next to the For loop in its respective section.

Cycles

1. While: it will execute all the commands specified between do and done as long as the condition is true. If we want to pass comparison operators to it, the expression must be in brackets.

while CONDITION / COMMAND do commands done

Example: multiplication table of a number

#! / bin / bash X = 1 echo "Enter a number and press ENTER" read M #The loop controls that X is less than or equal to 10 while [$ X –le 10] do #In R we store the multiplication of X by MR = $ [X * M] # This multiplication is printed on the screen echo "$ M * $ X = $ R" #With let, we increase the value of X by 1 unit let X = $ X + 1 done

2. For: stores a list of elements in a variable, which will be used to perform certain operations with each cycle.

for VARIABLE in ELEMENTS do commands done

Example: program that copies a file from one folder to another, replacing an old file.

# / bin / bash #We establish source and destination directories ORIGIN = / home / user / Downloads DESTINATION = / home / user / Documents # We position ourselves in the source cd $ ORIGIN #Of all the files, we only want the one that is # call FILE for FILE in * do ARCH-DESTINATION = "$ DESTINATION / $ FILE" # -f filters us regular files, since directories are #nothing good for us. –Nt filters out # files “newer” than those #found in the destination folder if [-f $ FILE] && [$ FILE –nt $ ARCH-DESTINATION]; then echo "Copying $ FILE ..." # we copy the file with cp cp $ FILE $ ARCH-DESTINATION fi done #We cd to exit the source folder cd

Another example: script where the user must guess a random number generated by the computer.

# / bin / bash #A random number is generated from 1 to 10, it is # saved in RANDOM RANDOM = $ [$ RANDOM% 10 + 1] while [1] do echo –n "Enter a number:" read NUM # Compare if the number chosen by the user is #equal to RANDOM; remember to use $ to evaluate the #values ​​of the variables and not their names if [“$ NUM –eq“ $ RANDOM ”]; then echo "You got it right!" #break allows ending the loop while break #If the number is less than RANDOM elif [“$ NUM –gt“ $ RANDOM ”]; then echo "It is less" "If not, it is greater than RANDOM else echo" IT IS greater "fi done

3. Until: quite similar in structure to While, except that the code always executes while the evaluation of the condition is negative, that is, the program continues executing "until the condition occurs"

until CONDITION / COMMAND do commands done

Example: print the numbers 10-20 in descending order

#! / bin / bash CONT = 20 #As long as the counter is less than 10 (-lt, “lower #than”) the code is executed until [$ CONT -lt 10]; do echo "COUNTER $ CONT" #A CONT is subtracted by a unit let CONT- = 1 done

4. Select: this last cycle is a special case, since it is generally used to make menus quickly. It works similar to the For loop.

select VARIABLE in LIST of commands done

Example: give the user the ability to continue or end the script.

#! / bin / bash #item is a variable that responds to what the #user chooses, Continue and Finish are the #options available to him, although other options can be added # more select item in Continue Finish do #If the user chooses end the program, then with break we exit the cycle. if [$ item = "Finish"]; then break fi done
Thank you Juan Carlos Ortiz!

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.   Medium Difficult said

    I think something like this: tar -cf - Directory | (cd / other / directory; tar -xvf -)

    Then it would look like / another / directory / Directory
    That way I compressed a Directory and you decompress it in another place….

  2.   Miguel Angel said

    Hello, good tuto, I am learning about the subject and everything is fine, only I have not been able to make a program that helps me, to see if you can help me please.

    I need to do a cycle, in which it will receive as parameters a list of a source file, this list only brings names (without extension), so that the cycle does the following, look for said name received in a directory (which is the one we will look for) , extract and copy the file (full name already with extension) and the absolute path and create it in another destination file.

    So far I have the following:

    while read line
    do
    echo -e "$ line"
    find / home / myuser / dof "$ line" -exec readlink -f {};
    done <testlist.txt So far I read the file, every line it has, but I can't make it look for that file and extract the information, if you can help me please, thank you. Cheers

  3.   Pamela galaviz said

    Thank you very much for the contribution 🙂

  4.   Mario Xavier said

    hi ... I hope you can help in the next practice ... Unzip file in tgz in the specified directory, in addition to specifying user and group for all existing directories and files, and assigning permissions to files and directories
    note: files ready for reading and writing
    directories execution permission

  5.   Juank said

    ARCH-DESTINATION is a variable in which we want to save the path of the destination file. Then, to this variable we indicate the variable DESTINATION, which above contains the path to the Documents folder and we add the "variable" FILE, which contains the name of the file. If that file were, for example, list.doc, the variable ARCH-DESTINATION would be equal to /home/Usuario/Documentos/listado.doc

  6.   Let's use Linux said

    It is the previous article. You can access it at http://usemoslinux.blogspot.com

    Hug! Paul.

  7.   Frank said

    Good morning mate just thank you, your blog is very good, but I can't get the first part of Programming in Bash, where I get it thanks, greetings

  8.   Saito Mordraw said

    Two extraordinary parts, my sincere congratulations.

    Simply wonderful.

  9.   Fredy said

    All right

  10.   Hugo said

    Hello, I'm making a program with a CASE, what I want it to do and I don't know how, for example:

    echo Picks an option:
    threw out
    echo 1. option 1
    echo 2. option 2
    echo 3. option 3
    echo 4. option 4
    echo 5. Exit
    readvar
    case "$ var" in
    1)
    echo "You selected option 1"
    ;;
    2)
    echo "You selected option 2"
    ;;
    3)
    threw out "….."
    ;;
    4)
    threw out "…."
    ;;
    5)
    threw out "…"

    ;;
    *)
    echo "wrong option"
    ;;
    esac

    Ok, what I don't know how to do is that when I select option 4, which is to exit, ask if I really want to exit, and give me 2 options.

    and the other is that when you select something other than the numbers 1..5 do not vote for me from the script….

    Could you help me thanks.

  11.   DAPAMA21 said

    Hi, I started scripting 1 month ago and thanks to your script posts. I will have done about 15-20. Thank you very much in advance. But now our teacher has given us a job of which I have become stagnant. Since the teacher asks:
    passing a directory, copy to your home all the files that are in that directory alphabetically and naming them file1 file2 etc ... etc ...
    Now I am at the moment of find or locate, I wanted to use find but when giving it error code as I put it through dev null, the permissions denied then I get wrong and putting the locate I am here:
    locate $ 1 | grep "/ $ {1} \ $"
    but of course with this they all come out ...
    Thank you very much if you read it.
    If you can help me it would be a great favor.

  12.   Luis said

    I would like you to help me with this.
    1.-Enter a whole number on the keyboard and display twice and triple that number on the screen. 2.- Make a program to decide if a number entered by keyboard is divisible by 3 or not.
    3.- Make a program to find the sum of: ???????? + ???????? + ???????? + ???????? + ⋯? ???????
    4.- Make a program to find the sum 1 + 3 + 5 + 7 + 9 · · · + (2n + 1).
    5.-Make a program that prints the word Linux on the screen 10 times
    6.-Make a program that prints the word Linux on the screen the number of times indicated by a user.
    7.-Enter an amount in hours and convert them to minutes and seconds.
    8.-Calculate the area of ​​a triangle
    9.-Enter a number by keyboard, then if you enter 2 it should be squared, 3 cubed, 4 to the fourth and so on up to 6.
    10-Calculate the pension that a student must pay, the specialty code must be entered, and the days in arrears:
    CODE
    SPECIALTY
    RODE
    DURING PER DAY
    1
    COMPUTING
    160
    1
    2
    NURSING
    150
    1.5
    3
    SECRETARIAT
    140
    2
    4
    TOURISM
    180
    2.5
    5
    ACCOUNTING
    160
    1
    You must show the specialty you are studying, the cost of the pension, the default and the total amount to be paid.

  13.   Charly said

    Hello, can someone help me?
    I need «Request three words by keyboard and display them in alphabetical order from A to z»
    In Bash or sh language for LINUX porfaborrrr